~ chicken-core (master) /manual/Module (scheme base)
Trap1[[tags: manual]]2[[toc:]]34== Module scheme56This module provides all of CHICKEN's R7RS procedures and macros.7These descriptions are based directly on the ''Revised^7 Report on the8Algorithmic Language Scheme''.910== Expressions1112Expression types are categorized as primitive or derived. Primitive13expression types include variables and procedure calls. Derived14expression types are not semantically primitive, but can instead be15defined as macros. The distinction which R7RS makes between primitive16and derived is unimportant and does not necessarily reflect how it is17implemented in CHICKEN itself.1819=== Primitive expression types2021==== Variable references2223<macro><variable></macro><br>2425An expression consisting of a variable is a variable reference. The26value of the variable reference is the value stored in the location to27which the variable is bound. It is an error to reference an unbound28variable.2930 (define x 28)31 x ===> 283233==== Literal expressions3435<macro>(quote <datum>)</macro><br>36<macro>'<datum></macro><br>37<macro><constant></macro><br>3839(quote <datum>) evaluates to <datum>. <Datum> may be any external40representation of a Scheme object. This notation is used to include41literal constants in Scheme code.4243 (quote a) ===> a44 (quote #(a b c)) ===> #(a b c)45 (quote (+ 1 2)) ===> (+ 1 2)4647(quote <datum>) may be abbreviated as '<datum>. The two notations are48equivalent in all respects.4950 'a ===> a51 '#(a b c) ===> #(a b c)52 '() ===> ()53 '(+ 1 2) ===> (+ 1 2)54 '(quote a) ===> (quote a)55 ''a ===> (quote a)5657Numerical constants, string constants, character constants, and boolean58constants evaluate "to themselves"; they need not be quoted.5960 '"abc" ===> "abc"61 "abc" ===> "abc"62 '145932 ===> 14593263 145932 ===> 14593264 '#t ===> #t65 #t ===> #t66 '#(a 10) ===> #(a 10)67 #(a 10) ===> #(a 10)68 '#u8(64 65) ===> #u8(64 65)69 #u8(64 65) ===> #u8(64 65)7071It is an error to alter a constant (i.e. the value of a literal72expression) using a mutation procedure like set-car! or string-set!.73In the current implementation of CHICKEN, identical constants don't74share memory and it is possible to mutate them, but this may change in75the future.7677==== Procedure calls7879<macro>(<operator> <operand[1]> ...)</macro><br>8081A procedure call is written by simply enclosing in parentheses82expressions for the procedure to be called and the arguments to be83passed to it. The operator and operand expressions are evaluated (in an84unspecified order) and the resulting procedure is passed the resulting85arguments.8687 (+ 3 4) ===> 788 ((if #f + *) 3 4) ===> 128990A number of procedures are available as the values of variables in the91initial environment; for example, the addition and multiplication92procedures in the above examples are the values of the variables + and93*. New procedures are created by evaluating lambda94expressions. Procedure calls may return any number of values (see the95{{values}} procedure [[#control-features|below]]).9697Procedure calls are also called combinations.9899Note: In contrast to other dialects of Lisp, the order of100evaluation is unspecified, and the operator expression and the101operand expressions are always evaluated with the same evaluation102rules.103104Note: Although the order of evaluation is otherwise unspecified,105the effect of any concurrent evaluation of the operator and operand106expressions is constrained to be consistent with some sequential107order of evaluation. The order of evaluation may be chosen108differently for each procedure call.109110Note: In many dialects of Lisp, the empty combination, (), is a111legitimate expression. In Scheme, combinations must have at least112one subexpression, so () is not a syntactically valid expression.113114==== Procedures115116<macro>(lambda <formals> <body>)</macro><br>117118Syntax: <Formals> should be a formal arguments list as described below,119and <body> should be a sequence of one or more expressions.120121Semantics: A lambda expression evaluates to a procedure. The122environment in effect when the lambda expression was evaluated is123remembered as part of the procedure. When the procedure is later called124with some actual arguments, the environment in which the lambda125expression was evaluated will be extended by binding the variables in126the formal argument list to fresh locations, the corresponding actual127argument values will be stored in those locations, and the expressions128in the body of the lambda expression will be evaluated sequentially in129the extended environment. The result(s) of the last expression in the130body will be returned as the result(s) of the procedure call.131132 (lambda (x) (+ x x)) ===> a procedure133 ((lambda (x) (+ x x)) 4) ===> 8134135 (define reverse-subtract136 (lambda (x y) (- y x)))137 (reverse-subtract 7 10) ===> 3138139 (define add4140 (let ((x 4))141 (lambda (y) (+ x y))))142 (add4 6) ===> 10143144<Formals> should have one of the following forms:145146* (<variable[1]> ...): The procedure takes a fixed number of147 arguments; when the procedure is called, the arguments will be148 stored in the bindings of the corresponding variables.149150* <variable>: The procedure takes any number of arguments; when the151 procedure is called, the sequence of actual arguments is converted152 into a newly allocated list, and the list is stored in the binding153 of the <variable>.154155* (<variable[1]> ... <variable[n]> . <variable[n+1]>): If a156 space-delimited period precedes the last variable, then the157 procedure takes n or more arguments, where n is the number of158 formal arguments before the period (there must be at least one).159 The value stored in the binding of the last variable will be a160 newly allocated list of the actual arguments left over after all161 the other actual arguments have been matched up against the other162 formal arguments.163164It is an error for a <variable> to appear more than once in <formals>.165166 ((lambda x x) 3 4 5 6) ===> (3 4 5 6)167 ((lambda (x y . z) z)168 3 4 5 6) ===> (5 6)169170Each procedure created as the result of evaluating a lambda expression171is (conceptually) tagged with a storage location, in order to make eqv?172and eq? work on procedures.173174As an extension to R7RS, CHICKEN also supports "extended" DSSSL style175parameter lists, which allows embedded special keywords. Such a176keyword gives a special meaning to the {{<formal>}} it precedes.177DSSSL parameter lists are defined by the following grammar:178179 <parameter-list> ==> <required-parameter>*180 [#!optional <optional-parameter>*]181 [#!rest <rest-parameter>]182 [#!key <keyword-parameter>*]183 <required-parameter> ==> <ident>184 <optional-parameter> ==> <ident>185 | (<ident> <initializer>)186 <rest-parameter> ==> <ident>187 <keyword-parameter> ==> <ident>188 | (<ident> <initializer>)189 <initializer> ==> <expr>190191When a procedure is applied to a list of arguments, the parameters and arguments are processed from left to right as follows:192193* Required-parameters are bound to successive arguments starting with the first argument. It shall be an error if there are fewer arguments than required-parameters.194* Next, the optional-parameters are bound with the remaining arguments. If there are fewer arguments than optional-parameters, then the remaining optional-parameters are bound to the result of the evaluation of their corresponding <initializer>, if one was specified, otherwise {{#f}}. The corresponding <initializer> is evaluated in an environment in which all previous parameters have been bound.195* If there is a rest-parameter, then it is bound to a list containing all the remaining arguments left over after the argument bindings with required-parameters and optional-parameters have been made.196* If {{#!key}} was specified in the parameter-list, there should be an even number of remaining arguments. These are interpreted as a series of pairs, where the first member of each pair is a keyword specifying the parameter name, and the second member is the corresponding value. If the same keyword occurs more than once in the list of arguments, then the corresponding value of the first keyword is the binding value. If there is no argument for a particular keyword-parameter, then the variable is bound to the result of evaluating <initializer>, if one was specified, otherwise {{#f}}. The corresponding <initializer> is evaluated in an environment in which all previous parameters have been bound.197198Needing a special mention is the close relationship between the199rest-parameter and possible keyword-parameters. Declaring a200rest-parameter binds up all remaining arguments in a list, as201described above. These same remaining arguments are also used for202attempted matches with declared keyword-parameters, as described203above, in which case a matching keyword-parameter binds to the204corresponding value argument at the same time that both the keyword205and value arguments are added to the rest parameter list. Note that206for efficiency reasons, the keyword-parameter matching does nothing207more than simply attempt to match with pairs that may exist in the208remaining arguments. Extra arguments that don't match are simply209unused and forgotten if no rest-parameter has been declared. Because210of this, the caller of a procedure containing one or more211keyword-parameters cannot rely on any kind of system error to report212wrong keywords being passed in.213214It shall be an error for an {{<ident>}} to appear more than once in a215parameter-list.216217If there is no rest-parameter and no keyword-parameters in the parameter-list, then it shall be an error for any extra arguments to be passed to the procedure.218219220Example:221222 ((lambda x x) 3 4 5 6) => (3 4 5 6)223 ((lambda (x y #!rest z) z)224 3 4 5 6) => (5 6)225 ((lambda (x y #!optional z #!rest r #!key i (j 1))226 (list x y z i: i j: j))227 3 4 5 i: 6 i: 7) => (3 4 5 i: 6 j: 1)228229230231==== Conditionals232233<macro>(if <test> <consequent> <alternate>)</macro><br>234<macro>(if <test> <consequent>)</macro><br>235236Syntax: <Test>, <consequent>, and <alternate> may be arbitrary237expressions.238239Semantics: An if expression is evaluated as follows: first, <test> is240evaluated. If it yields a true value (see [[#Booleans|the section241about booleans]] below), then <consequent> is evaluated and its242value(s) is(are) returned. Otherwise <alternate> is evaluated and its243value(s) is(are) returned. If <test> yields a false value and no244<alternate> is specified, then the result of the expression is245unspecified.246247 (if (> 3 2) 'yes 'no) ===> yes248 (if (> 2 3) 'yes 'no) ===> no249 (if (> 3 2)250 (- 3 2)251 (+ 3 2)) ===> 1252253==== Assignments254255<macro>(set! <variable> <expression>)</macro><br>256257<Expression> is evaluated, and the resulting value is stored in the258location to which <variable> is bound. <Variable> must be bound either259in some region enclosing the set! expression or at top level. The260result of the set! expression is unspecified.261262 (define x 2)263 (+ x 1) ===> 3264 (set! x 4) ===> unspecified265 (+ x 1) ===> 5266267As an extension to R7RS, {{set!}} for unbound toplevel variables is268allowed. Also, {{(set! (PROCEDURE ...) ...)}} is supported, as CHICKEN269implements [[http://srfi.schemers.org/srfi-17/srfi-17.html|SRFI-17]].270271==== Inclusion272273<macro>(include STRING1 STRING2 ...)</macro>274<macro>(include-ci STRING1 STRING2 ...)</macro>275276Semantics: Both {{include}} and {{include-ci}} take one or277more filenames expressed as string literals, apply an278implementation-specific algorithm to find corresponding279files, read the contents of the files in the specified order280as if by repeated applications of {{read}}, and effectively replace the {{include}}281or {{include-ci}} expression with a {{begin}}282expression containing what was read from the files. The283difference between the two is that {{include-ci}} reads each284file as if it began with the {{#!fold-case}} directive, while285{{include}} does not.286287288=== Derived expression types289290The constructs in this section are hygienic. For reference purposes,291these macro definitions will convert most of the constructs described292in this section into the primitive constructs described in the293previous section. This does not necessarily mean that's exactly how294it's implemented in CHICKEN.295296==== Conditionals297298<macro>(cond <clause[1]> <clause[2]> ...)</macro><br>299300Syntax: Each <clause> should be of the form301302 (<test> <expression[1]> ...)303304where <test> is any expression. Alternatively, a <clause> may be of the305form306307 (<test> => <expression>)308309The last <clause> may be an "else clause," which has the form310311 (else <expression[1]> <expression[2]> ...).312313Semantics: A cond expression is evaluated by evaluating the <test>314expressions of successive <clause>s in order until one of them315evaluates to a true value (see [[#Booleans|the section about316booleans]] below). When a <test> evaluates to a true value, then the317remaining <expression>s in its <clause> are evaluated in order, and318the result(s) of the last <expression> in the <clause> is(are)319returned as the result(s) of the entire cond expression. If the320selected <clause> contains only the <test> and no <expression>s, then321the value of the <test> is returned as the result. If the selected322<clause> uses the => alternate form, then the <expression> is323evaluated. Its value must be a procedure that accepts one argument;324this procedure is then called on the value of the <test> and the325value(s) returned by this procedure is(are) returned by the cond326expression. If all <test>s evaluate to false values, and there is no327else clause, then the result of the conditional expression is328unspecified; if there is an else clause, then its <expression>s are329evaluated, and the value(s) of the last one is(are) returned.330331 (cond ((> 3 2) 'greater)332 ((< 3 2) 'less)) ===> greater333 (cond ((> 3 3) 'greater)334 ((< 3 3) 'less)335 (else 'equal)) ===> equal336 (cond ((assv 'b '((a 1) (b 2))) => cadr)337 (else #f)) ===> 2338339340As an extension to R7RS, CHICKEN also supports the341[[http://srfi.schemers.org/srfi-61|SRFI-61]] syntax:342343 (<generator> <guard> => <expression>)344345In this situation, {{generator}} is ''always'' evaluated. Its346resulting value(s) are used as argument(s) for the {{guard}}347procedure. Finally, if {{guard}} returns a non-{{#f}} value, the348{{expression}} is evaluated by calling it with the result of349{{guard}}. Otherwise, evaluation procedes to the next clause.350351<macro>(case <key> <clause[1]> <clause[2]> ...)</macro><br>352353Syntax: <Key> may be any expression. Each <clause> should have the form354355 ((<datum[1]> ...) <expression[1]> <expression[2]> ...),356357where each <datum> is an external representation of some object.358Alternatively, as per R7RS, a <clause> may be of the form359360 ((<datum[1]> ...) => <expression>).361362All the <datum>s must be distinct. The last <clause> may be an363"else clause," which has one of the following two forms:364365 (else <expression[1]> <expression[2]> ...)366 (else => <expression>).367368Semantics: A case expression is evaluated as follows. <Key> is369evaluated and its result is compared against each <datum>. If the370result of evaluating <key> is equivalent (in the sense of {{eqv?}};371see [[#equivalence-predicates|below]]) to a <datum>, then the372expressions in the corresponding <clause> are evaluated from left to373right and the result(s) of the last expression in the <clause> is(are)374returned as the result(s) of the case expression. If the selected375<clause> uses the => alternate form (an R7RS extension), then the376<expression> is evaluated. Its value must be a procedure that accepts377one argument; this procedure is then called on the value of the <key>378and the value(s) returned by this procedure is(are) returned by the379case expression. If the result of evaluating <key> is different from380every <datum>, then if there is an else clause its expressions are381evaluated and the result(s) of the last is(are) the result(s) of the382case expression; otherwise the result of the case expression is383unspecified.384385 (case (* 2 3)386 ((2 3 5 7) 'prime)387 ((1 4 6 8 9) 'composite)) ===> composite388 (case (car '(c d))389 ((a) 'a)390 ((b) 'b)) ===> unspecified391 (case (car '(c d))392 ((a e i o u) 'vowel)393 ((w y) 'semivowel)394 (else 'consonant)) ===> consonant395396<macro>(and <test[1]> ...)</macro><br>397398The <test> expressions are evaluated from left to right, and the value399of the first expression that evaluates to a false value (see400[[#Booleans|the section about booleans]]) is returned. Any remaining401expressions are not evaluated. If all the expressions evaluate to true402values, the value of the last expression is returned. If there are no403expressions then #t is returned.404405 (and (= 2 2) (> 2 1)) ===> #t406 (and (= 2 2) (< 2 1)) ===> #f407 (and 1 2 'c '(f g)) ===> (f g)408 (and) ===> #t409410<macro>(or <test[1]> ...)</macro><br>411412The <test> expressions are evaluated from left to right, and the value413of the first expression that evaluates to a true value (see414[[#Booleans|the section about booleans]]) is returned. Any remaining415expressions are not evaluated. If all expressions evaluate to false416values, the value of the last expression is returned. If there are no417expressions then #f is returned.418419 (or (= 2 2) (> 2 1)) ===> #t420 (or (= 2 2) (< 2 1)) ===> #t421 (or #f #f #f) ===> #f422 (or (memq 'b '(a b c))423 (/ 3 0)) ===> (b c)424425<macro>(unless TEST EXP1 EXP2 ...)</macro>426427Equivalent to:428429<enscript highlight=scheme>430(if (not TEST) (begin EXP1 EXP2 ...))431</enscript>432433<macro>(when TEST EXP1 EXP2 ...)</macro>434435Equivalent to:436437<enscript highlight=scheme>438(if TEST (begin EXP1 EXP2 ...))439</enscript>440441<macro>(cond-expand <ce-clause1> <ce-clause2> ...)</macro>442443The {{cond-expand}} expression type provides a way444to statically expand different expressions depending on the445implementation. A <ce-clause> takes the following form:446447{{448(<feature requirement> <expression> ...)449}}450451The last clause can be an "else clause," which has the form452453{{454(else <expression> ...)455}}]456457A feature requirement takes one of the following forms:458459<feature identifier>460461{{(library <library name>)}}462463{{(and <feature requirement> ...)}}464465{{(or <feature requirement> ...)}}466467{{(not <feature requirement>)}}468469Each implementation maintains a list of470feature identifiers which are present, as well as a list471of libraries which can be imported.472The value of a <feature requirement> is determined by replacing each473<feature identifier> and {{(library <library name>)}} on the474implementation's lists with {{#t}}, and all other feature identifiers and library names with {{#f}}, then evaluating the resulting expression as a Scheme boolean expression under475the normal interpretation of {{and}}, {{or}}, and {{not}}.476477A {{cond-expand}} is then expanded by evaluating the478<feature requirement>s of successive <ce-clause>s in order479until one of them returns {{#t}}. When a true clause is found,480the corresponding <expression>s are expanded to a {{begin}},481and the remaining clauses are ignored.482483If none of the484<feature requirement>s evaluate to {{#t}}, then if there is an485{{else}} clause, its <expression>s are included. Otherwise, the486behavior of the {{cond}}-expand is unspecified. Unlike {{cond}},487{{cond-expand}} does not depend on the value of any variables.488489The following features are built-in and always available by default:490{{chicken}}, {{srfi-0}}, {{srfi-2}}, {{srfi-6}}, {{srfi-8}}, {{srfi-9}},491{{srfi-11}}, {{srfi-12}}, {{srfi-15}}, {{srfi-16}}, {{srfi-17}}, {{srfi-23}},492{{srfi-26}}, {{srfi-28}}, {{srfi-30}}, {{srfi-31}}, {{srfi-39}}, {{srfi-46}},493{{srfi-55}}, {{srfi-61}}, {{srfi-62}}, {{srfi-87}}, {{srfi-88}}.494495There are also situation-specific feature identifiers: {{compiling}} during496compilation, {{csi}} when running in the interpreter, and {{compiler-extension}}497when running within the compiler.498499The symbols returned by the following procedures from500[[Module (chicken platform)|(chicken platform)]] are also available501as feature-identifiers in all situations: {{(machine-byte-order)}},502{{(machine-type)}}, {{(software-type)}}, {{(software-version)}}. For503example, the {{machine-type}} class of feature-identifiers include504{{arm}}, {{alpha}}, {{mips}}, etc.505506Platform endianness is indicated by the {{little-endian}} and {{big-endian}}507features.508509In addition the following feature-identifiers may exist: {{cross-chicken}},510{{dload}}, {{gchooks}}, {{ptables}}, {{case-insensitive}}.511512513==== Binding constructs514515The three binding constructs let, let*, and letrec give Scheme a block516structure, like Algol 60. The syntax of the three constructs is517identical, but they differ in the regions they establish for their518variable bindings. In a let expression, the initial values are computed519before any of the variables become bound; in a let* expression, the520bindings and evaluations are performed sequentially; while in a letrec521expression, all the bindings are in effect while their initial values522are being computed, thus allowing mutually recursive definitions.523524<macro>(let <bindings> <body>)</macro><br>525526Syntax: <Bindings> should have the form527528 ((<variable[1]> <init[1]>) ...),529530where each <init> is an expression, and <body> should be a sequence of531one or more expressions. It is an error for a <variable> to appear more532than once in the list of variables being bound.533534Semantics: The <init>s are evaluated in the current environment (in535some unspecified order), the <variable>s are bound to fresh locations536holding the results, the <body> is evaluated in the extended537environment, and the value(s) of the last expression of <body> is(are)538returned. Each binding of a <variable> has <body> as its region.539540 (let ((x 2) (y 3))541 (* x y)) ===> 6542543 (let ((x 2) (y 3))544 (let ((x 7)545 (z (+ x y)))546 (* z x))) ===> 35547548See also "named let", [[#iteration|below]].549550<macro>(let* <bindings> <body>)</macro><br>551552Syntax: <Bindings> should have the form553554 ((<variable[1]> <init[1]>) ...),555556and <body> should be a sequence of one or more expressions.557558Semantics: Let* is similar to let, but the bindings are performed559sequentially from left to right, and the region of a binding indicated560by (<variable> <init>) is that part of the let* expression to the right561of the binding. Thus the second binding is done in an environment in562which the first binding is visible, and so on.563564 (let ((x 2) (y 3))565 (let* ((x 7)566 (z (+ x y)))567 (* z x))) ===> 70568569<macro>(letrec <bindings> <body>)</macro><br>570571Syntax: <Bindings> should have the form572573 ((<variable[1]> <init[1]>) ...),574575and <body> should be a sequence of one or more expressions. It is an576error for a <variable> to appear more than once in the list of577variables being bound.578579Semantics: The <variable>s are bound to fresh locations holding580undefined values, the <init>s are evaluated in the resulting581environment (in some unspecified order), each <variable> is assigned to582the result of the corresponding <init>, the <body> is evaluated in the583resulting environment, and the value(s) of the last expression in584<body> is(are) returned. Each binding of a <variable> has the entire585letrec expression as its region, making it possible to define mutually586recursive procedures.587588 (letrec ((even?589 (lambda (n)590 (if (zero? n)591 #t592 (odd? (- n 1)))))593 (odd?594 (lambda (n)595 (if (zero? n)596 #f597 (even? (- n 1))))))598 (even? 88))599 ===> #t600601One restriction on letrec is very important: it must be possible to602evaluate each <init> without assigning or referring to the value of any603<variable>. If this restriction is violated, then it is an error. The604restriction is necessary because Scheme passes arguments by value605rather than by name. In the most common uses of letrec, all the <init>s606are lambda expressions and the restriction is satisfied automatically.607608<macro>(letrec* <bindings> <body>) </macro>609610Syntax: <Bindings> has the form {{((<variable[1]> <init[1]>) ...)}}, and611<body> is a sequence of zero or more612definitions followed by one or more expressions as described in section 4.1.4.613It is an error for a <variable> to appear more than once in the list of614variables being bound.615616Semantics: The <variable>s are bound to fresh locations, each <variable> is617assigned in left-to-right order to the result of evaluating the corresponding618<init> (interleaving evaluations and assignments), the <body> is evaluated in619the resulting environment, and the values of the last expression in <body> are620returned. Despite the left-to-right evaluation and assignment order, each621binding of a <variable> has the entire letrec* expression as its region, making622it possible to define mutually recursive procedures.623624If it is not possible to evaluate each <init> without assigning or referring to625the value of the corresponding <variable> or the <variable> of any of the626bindings that follow it in <bindings>, it is an error. Another restriction is627that it is an error to invoke the continuation of an <init> more than once.628629 ;; Returns the arithmetic, geometric, and630 ;; harmonic means of a nested list of numbers631 (define (means ton)632 (letrec*633 ((mean634 (lambda (f g)635 (f (/ (sum g ton) n))))636 (sum637 (lambda (g ton)638 (if (null? ton)639 (+)640 (if (number? ton)641 (g ton)642 (+ (sum g (car ton))643 (sum g (cdr ton)))))))644 (n (sum (lambda (x) 1) ton)))645 (values (mean values values)646 (mean exp log)647 (mean / /))))648649Evaluating {{(means '(3 (1 4)))}} returns three values: 8/3, 2.28942848510666650(approximately), and 36/19.651652<macro>(let-values <mv binding spec> <body>)</macro>653654Syntax: <Mv binding spec> has the form {{((<formals[1]> <init[1]>) ...)}},655where each <init> is an expression, and <body> is656zero or more definitions followed by a sequence of one or more expressions as657described in section 4.1.4. It is an error for a variable to appear more than658once in the set of <formals>.659660Semantics: The <init>s are evaluated in the current environment (in some661unspecified order) as if by invoking call-with-values, and the variables662occurring in the <formals> are bound to fresh locations holding the values663returned by the <init>s, where the <formals> are matched to the return values664in the same way that the <formals> in a lambda expression are matched to the665arguments in a procedure call. Then, the <body> is evaluated in the extended666environment, and the values of the last expression of <body> are returned. Each667binding of a <variable> has <body> as its region.668669It is an error if the <formals> do not match the number of values returned by670the corresponding <init>.671672 (let-values (((root rem) (exact-integer-sqrt 32)))673 (* root rem)) ==> 35674675<macro>(let*-values <mv binding spec> <body>)</macro>676677Syntax: <Mv binding spec> has the form {{((<formals> <init>) ...)}},678and <body> is a sequence of zero or more definitions679followed by one or more expressions as described in section 4.1.4. In each680<formals>, it is an error if any variable appears more than once.681682Semantics: The let*-values construct is similar to let-values, but the <init>s683are evaluated and bindings created sequentially from left to right, with the684region of the bindings of each <formals> including the <init>s to its right as685well as <body>. Thus the second <init> is evaluated in an environment in which686the first set of bindings is visible and initialized, and so on.687688 (let ((a 'a) (b 'b) (x 'x) (y 'y))689 (let*-values (((a b) (values x y))690 ((x y) (values a b)))691 (list a b x y))) ===> (x y x y)692693==== Sequencing694695<macro>(begin <expression[1]> <expression[2]> ...)</macro><br>696697The <expression>s are evaluated sequentially from left to right, and698the value(s) of the last <expression> is(are) returned. This expression699type is used to sequence side effects such as input and output.700701 (define x 0)702703 (begin (set! x 5)704 (+ x 1)) ===> 6705706 (begin (display "4 plus 1 equals ")707 (display (+ 4 1))) ===> unspecified708 and prints 4 plus 1 equals 5709710As an extension to R7RS, CHICKEN also allows {{(begin)}} without body711expressions in any context, not just at toplevel. This simply712evaluates to the unspecified value.713714715==== Iteration716717<macro>(do ((<variable[1]> <init[1]> <step[1]>) ...) (<test> <expression> ...) <command> ...)</macro><br>718719Do is an iteration construct. It specifies a set of variables to be720bound, how they are to be initialized at the start, and how they are to721be updated on each iteration. When a termination condition is met, the722loop exits after evaluating the <expression>s.723724Do expressions are evaluated as follows: The <init> expressions are725evaluated (in some unspecified order), the <variable>s are bound to726fresh locations, the results of the <init> expressions are stored in727the bindings of the <variable>s, and then the iteration phase begins.728729Each iteration begins by evaluating <test>; if the result is false730(see [[#Booleans|the section about booleans]]), then the <command>731expressions are evaluated in order for effect, the <step> expressions732are evaluated in some unspecified order, the <variable>s are bound to733fresh locations, the results of the <step>s are stored in the bindings734of the <variable>s, and the next iteration begins.735736If <test> evaluates to a true value, then the <expression>s are737evaluated from left to right and the value(s) of the last <expression>738is(are) returned. If no <expression>s are present, then the value of739the do expression is unspecified.740741The region of the binding of a <variable> consists of the entire do742expression except for the <init>s. It is an error for a <variable> to743appear more than once in the list of do variables.744745A <step> may be omitted, in which case the effect is the same as if746(<variable> <init> <variable>) had been written instead of (<variable>747<init>).748749 (do ((vec (make-vector 5))750 (i 0 (+ i 1)))751 ((= i 5) vec)752 (vector-set! vec i i)) ===> #(0 1 2 3 4)753754 (let ((x '(1 3 5 7 9)))755 (do ((x x (cdr x))756 (sum 0 (+ sum (car x))))757 ((null? x) sum))) ===> 25758759<macro>(let <variable> <bindings> <body>)</macro><br>760761"Named let" is a variant on the syntax of let which provides a more762general looping construct than do and may also be used to express763recursions. It has the same syntax and semantics as ordinary let except764that <variable> is bound within <body> to a procedure whose formal765arguments are the bound variables and whose body is <body>. Thus the766execution of <body> may be repeated by invoking the procedure named by767<variable>.768769 (let loop ((numbers '(3 -2 1 6 -5))770 (nonneg '())771 (neg '()))772 (cond ((null? numbers) (list nonneg neg))773 ((>= (car numbers) 0)774 (loop (cdr numbers)775 (cons (car numbers) nonneg)776 neg))777 ((< (car numbers) 0)778 (loop (cdr numbers)779 nonneg780 (cons (car numbers) neg)))))781 ===> ((6 1 3) (-5 -2))782783==== Dynamic bindings784785The dynamic extent of a procedure call is the time between when it is initiated786and when it returns. In Scheme, {{call-with-current-continuation}}787allows reentering a dynamic extent after its procedure call has returned. Thus,788the dynamic extent of a call might not be a single, continuous time period.789790This sections introduces parameter objects, which can be bound to new values791for the duration of a dynamic extent. The set of all parameter bindings at a792given time is called the dynamic environment.793794<procedure>(make-parameter init [converter])</procedure>795796Returns a newly allocated parameter object, which is a procedure that accepts797zero arguments and returns the value associated with the parameter object.798Initially, this value is the value of {{(converter init)}}, or of {{init}}799if the conversion procedure {{converter}} is not specified. The associated value can be temporarily changed800using {{parameterize}}, which is described below.801802The effect of passing arguments to a parameter object is803implementation-dependent.804805<syntax>(parameterize ((<param[1]> <value[1]>) ...) <body>)</syntax>806807Syntax: Both <param[1]> and <value[1]> are expressions.808809It is an error if the value of any <param> expression is not a parameter810object.811812Semantics: A parameterize expression is used to change the values returned by813specified parameter objects during the evaluation of the body.814815The <param> and <value> expressions are evaluated in an unspecified order. The816<body> is evaluated in a dynamic environment in which calls to the parameters817return the results of passing the corresponding values to the conversion818procedure specified when the parameters were created. Then the previous values819of the parameters are restored without passing them to the conversion820procedure. The results of the last expression in the <body> are returned as the821results of the entire parameterize expression.822823Note: If the conversion procedure is not idempotent, the results of824(parameterize ((x (x))) ...), which appears to bind the parameter825826x to its current value, might not be what the user expects.827828If an implementation supports multiple threads of execution, then parameterize829must not change the associated values of any parameters in any thread other830than the current thread and threads created inside <body>.831832Parameter objects can be used to specify configurable settings for a833computation without the need to pass the value to every procedure in the call834chain explicitly.835836 (define radix837 (make-parameter838 10839 (lambda (x)840 (if (and (exact-integer? x) (<= 2 x 16))841 x842 (error "invalid radix")))))843844 (define (f n) (number->string n (radix)))845846 (f 12) ==> "12"847 (parameterize ((radix 2))848 (f 12)) ==> "1100"849 (f 12) ==> "12"850851 (radix 16) ==> unspecified852853 (parameterize ((radix 0))854 (f 12)) ==> error855856==== Exception handling857858<macro>(guard (<variable> <cond clause[1]> <cond clause[2]> ...) <body>)</macro>859860Syntax: Each <cond clause> is as in the specification of cond.861862Semantics: The <body> is evaluated with an exception handler that binds the863raised object (see {{raise}}) to <variable> and, within the scope864of that binding, evaluates the clauses as if they were the clauses of a cond865expression. That implicit cond expression is evaluated with the continuation866and dynamic environment of the guard expression. If every <cond clause>'s867<test> evaluates to #f and there is no else clause, then raise-continuable is868invoked on the raised object within the dynamic environment of the original869call to raise or raise-continuable, except that the current exception handler870is that of the guard expression.871872 (guard (condition873 ((assq 'a condition) => cdr)874 ((assq 'b condition)))875 (raise (list (cons 'a 42))))876 ==> 42877878 (guard (condition879 ((assq 'a condition) => cdr)880 ((assq 'b condition)))881 (raise (list (cons 'b 23))))882 ==> (b . 23)883884==== Quasiquotation885886<macro>(quasiquote <qq template>)</macro><br>887<macro>`<qq template></macro><br>888889"Backquote" or "quasiquote" expressions are useful for constructing890a list or vector structure when most but not all of the desired891structure is known in advance. If no commas appear within the <qq892template>, the result of evaluating `<qq template> is equivalent to the893result of evaluating '<qq template>. If a comma appears within the <qq894template>, however, the expression following the comma is evaluated895("unquoted") and its result is inserted into the structure instead of896the comma and the expression. If a comma appears followed immediately897by an at-sign (@), then the following expression must evaluate to a898list; the opening and closing parentheses of the list are then899"stripped away" and the elements of the list are inserted in place of900the comma at-sign expression sequence. A comma at-sign should only901appear within a list or vector <qq template>.902903 `(list ,(+ 1 2) 4) ===> (list 3 4)904 (let ((name 'a)) `(list ,name ',name))905 ===> (list a (quote a))906 `(a ,(+ 1 2) ,@(map abs '(4 -5 6)) b)907 ===> (a 3 4 5 6 b)908 `(( foo ,(- 10 3)) ,@(cdr '(c)) . ,(car '(cons)))909 ===> ((foo 7) . cons)910 `#(10 5 ,(sqrt 4) ,@(map sqrt '(16 9)) 8)911 ===> #(10 5 2 4 3 8)912913Quasiquote forms may be nested. Substitutions are made only for914unquoted components appearing at the same nesting level as the915outermost backquote. The nesting level increases by one inside each916successive quasiquotation, and decreases by one inside each917unquotation.918919 `(a `(b ,(+ 1 2) ,(foo ,(+ 1 3) d) e) f)920 ===> (a `(b ,(+ 1 2) ,(foo 4 d) e) f)921 (let ((name1 'x)922 (name2 'y))923 `(a `(b ,,name1 ,',name2 d) e))924 ===> (a `(b ,x ,'y d) e)925926The two notations `<qq template> and (quasiquote <qq template>) are927identical in all respects. ,<expression> is identical to (unquote928<expression>), and ,@<expression> is identical to (unquote-splicing929<expression>). The external syntax generated by write for two-element930lists whose car is one of these symbols may vary between931implementations.932933 (quasiquote (list (unquote (+ 1 2)) 4))934 ===> (list 3 4)935 '(quasiquote (list (unquote (+ 1 2)) 4))936 ===> `(list ,(+ 1 2) 4)937 i.e., (quasiquote (list (unquote (+ 1 2)) 4))938939Unpredictable behavior can result if any of the symbols quasiquote,940unquote, or unquote-splicing appear in positions within a <qq template>941otherwise than as described above.942943=== Macros944945Scheme programs can define and use new derived expression types, called946macros. Program-defined expression types have the syntax947948 (<keyword> <datum> ...)949950where <keyword> is an identifier that uniquely determines the951expression type. This identifier is called the syntactic keyword, or952simply keyword, of the macro. The number of the <datum>s, and their953syntax, depends on the expression type.954955Each instance of a macro is called a use of the macro. The set of rules956that specifies how a use of a macro is transcribed into a more957primitive expression is called the transformer of the macro.958959The macro definition facility consists of two parts:960961* A set of expressions used to establish that certain identifiers are962 macro keywords, associate them with macro transformers, and control963 the scope within which a macro is defined, and964965* a pattern language for specifying macro transformers.966967The syntactic keyword of a macro may shadow variable bindings, and968local variable bindings may shadow keyword bindings. All macros defined969using the pattern language are "hygienic" and "referentially970transparent" and thus preserve Scheme's lexical scoping:971972* If a macro transformer inserts a binding for an identifier973 (variable or keyword), the identifier will in effect be renamed974 throughout its scope to avoid conflicts with other identifiers.975 Note that a define at top level may or may not introduce a binding;976 this depends on whether the binding already existed before (in which977 case its value will be overridden).978979* If a macro transformer inserts a free reference to an identifier,980 the reference refers to the binding that was visible where the981 transformer was specified, regardless of any local bindings that982 may surround the use of the macro.983984==== Binding constructs for syntactic keywords985986Let-syntax and letrec-syntax are analogous to let and letrec, but they987bind syntactic keywords to macro transformers instead of binding988variables to locations that contain values. Syntactic keywords may also989be bound at top level.990991<macro>(let-syntax <bindings> <body>)</macro><br>992993Syntax: <Bindings> should have the form994995 ((<keyword> <transformer spec>) ...)996997Each <keyword> is an identifier, each <transformer spec> is an instance998of syntax-rules, and <body> should be a sequence of one or more999expressions. It is an error for a <keyword> to appear more than once in1000the list of keywords being bound.10011002Semantics: The <body> is expanded in the syntactic environment obtained1003by extending the syntactic environment of the let-syntax expression1004with macros whose keywords are the <keyword>s, bound to the specified1005transformers. Each binding of a <keyword> has <body> as its region.10061007 (let-syntax ((when (syntax-rules ()1008 ((when test stmt1 stmt2 ...)1009 (if test1010 (begin stmt11011 stmt2 ...))))))1012 (let ((if #t))1013 (when if (set! if 'now))1014 if)) ===> now10151016 (let ((x 'outer))1017 (let-syntax ((m (syntax-rules () ((m) x))))1018 (let ((x 'inner))1019 (m)))) ===> outer10201021<macro>(letrec-syntax <bindings> <body>)</macro><br>10221023Syntax: Same as for let-syntax.10241025Semantics: The <body> is expanded in the syntactic environment obtained1026by extending the syntactic environment of the letrec-syntax expression1027with macros whose keywords are the <keyword>s, bound to the specified1028transformers. Each binding of a <keyword> has the <bindings> as well as1029the <body> within its region, so the transformers can transcribe1030expressions into uses of the macros introduced by the letrec-syntax1031expression.10321033 (letrec-syntax1034 ((my-or (syntax-rules ()1035 ((my-or) #f)1036 ((my-or e) e)1037 ((my-or e1 e2 ...)1038 (let ((temp e1))1039 (if temp1040 temp1041 (my-or e2 ...)))))))1042 (let ((x #f)1043 (y 7)1044 (temp 8)1045 (let odd?)1046 (if even?))1047 (my-or x1048 (let temp)1049 (if y)1050 y))) ===> 710511052==== Pattern language10531054A <transformer spec> has the following form:10551056 (syntax-rules <literals> <syntax rule> ...)10571058Syntax: <Literals> is a list of identifiers and each <syntax rule>1059should be of the form10601061 (<pattern> <template>)10621063The <pattern> in a <syntax rule> is a list <pattern> that begins with1064the keyword for the macro.10651066A <pattern> is either an identifier, a constant, or one of the1067following10681069 (<pattern> ...)1070 (<pattern> <pattern> ... . <pattern>)1071 (<pattern> ... <pattern> <ellipsis> <pattern> ...)1072 #(<pattern> ...)1073 #(<pattern> ... <pattern> <ellipsis>)10741075and a template is either an identifier, a constant, or one of the1076following10771078 (<element> ...)1079 (<element> <element> ... . <template>)1080 (<ellipsis> <template>)1081 #(<element> ...)10821083where an <element> is a <template> optionally followed by an <ellipsis>1084and an <ellipsis> is the identifier "...".10851086Semantics: An instance of syntax-rules produces a new macro transformer1087by specifying a sequence of hygienic rewrite rules. A use of a macro1088whose keyword is associated with a transformer specified by1089syntax-rules is matched against the patterns contained in the <syntax1090rule>s, beginning with the leftmost <syntax rule>. When a match is1091found, the macro use is transcribed hygienically according to the1092template.10931094An identifier appearing within a <pattern> can be an underscore ({{_}}), a literal1095identifier listed in the list of <pattern literal>s, or the <ellipsis>. All1096other identifiers appearing within a <pattern> are pattern variables.10971098The keyword at the beginning of the pattern in a <syntax rule> is not involved1099in the matching and is considered neither a pattern variable nor a literal1100identifier.11011102Pattern variables match arbitrary input elements and are used to refer to1103elements of the input in the template. It is an error for the same pattern1104variable to appear more than once in a <pattern>.11051106Underscores also match arbitrary input elements but are not pattern variables1107and so cannot be used to refer to those elements. If an underscore appears in1108the <pattern literal>s list, then that takes precedence and underscores in the1109<pattern> match as literals. Multiple underscores can appear in a <pattern>.11101111Identifiers that appear in (<pattern literal> ...) are interpreted as literal1112identifiers to be matched against corresponding elements of the input. An1113element in the input matches a literal identifier if and only if it is an1114identifier and either both its occurrence in the macro expression and its1115occurrence in the macro definition have the same lexical binding, or the two1116identifiers are the same and both have no lexical binding.11171118A subpattern followed by <ellipsis> can match zero or more elements of the1119input, unless <ellipsis> appears in the <pattern literal>s, in which case it is1120matched as a literal.11211122More formally, an input form F matches a pattern P if and only if:11231124* P is an underscore (_).11251126* P is a non-literal identifier; or11271128* P is a literal identifier and F is an identifier with the same1129 binding; or11301131* P is a list (P[1] ... P[n]) and F is a list of n forms that match P1132 [1] through P[n], respectively; or11331134* P is an improper list (P[1] P[2] ... P[n] . P[n+1]) and F is a list1135 or improper list of n or more forms that match P[1] through P[n],1136 respectively, and whose nth "cdr" matches P[n+1]; or11371138* P is of the form (P[1] ... P[k] P[e] <ellipsis> P[m+1] ... P[n] . P[x]) where E1139 is a list or improper list of n elements, the first k of which match P[1]1140 through P[k], whose next m--k elements each match P[e], whose remaining n--m1141 elements match P[m+1] through P[n], and whose nth and final cdr matches P[x1142 ]; or11431144* P is a vector of the form #(P[1] ... P[n]) and F is a vector of n1145 forms that match P[1] through P[n]; or11461147* P is of the form #(P[1] ... P[k] P[e] <ellipsis> P[m+1] ... P[n]) where E is a1148 vector of n elements the first k of which match P[1] through P[k], whose1149 next m--k elements each match P[e], and whose remaining n--m elements match P1150 [m+1] through P[n]; or11511152* P is a datum and F is equal to P in the sense of the equal?1153 procedure.11541155It is an error to use a macro keyword, within the scope of its binding,1156in an expression that does not match any of the patterns.11571158When a macro use is transcribed according to the template of the matching1159<syntax rule>, pattern variables that occur in the template are replaced by the1160elements they match in the input. Pattern variables that occur in subpatterns1161followed by one or more instances of the identifier <ellipsis> are allowed only1162in subtemplates that are followed by as many instances of <ellipsis>. They are1163replaced in the output by all of the elements they match in the input,1164distributed as indicated. It is an error if the output cannot be built up as1165specified.11661167Identifiers that appear in the template but are not pattern variables or the1168identifier <ellipsis> are inserted into the output as literal identifiers. If a1169literal identifier is inserted as a free identifier then it refers to the1170binding of that identifier within whose scope the instance of syntax-rules1171appears. If a literal identifier is inserted as a bound identifier then it is1172in effect renamed to prevent inadvertent captures of free identifiers.11731174A template of the form (<ellipsis> <template>) is identical to <template>,1175except that ellipses within the template have no special meaning. That is, any1176ellipses contained within <template> are treated as ordinary identifiers. In1177particular, the template (<ellipsis> <ellipsis>) produces a single <ellipsis>.1178This allows syntactic abstractions to expand into code containing ellipses.11791180{{1181(define-syntax be-like-begin1182 (syntax-rules ()1183 ((be-like-begin name)1184 (define-syntax name1185 (syntax-rules ()1186 ((name expr (... ...))1187 (begin expr (... ...))))))))11881189(be-like-begin sequence)11901191(sequence 1 2 3 4) ==> 41192}}11931194As an example, if {{let}} and {{cond}} have their standard meaning1195then they are hygienic (as required) and the following is not an1196error.11971198 (let ((=> #f))1199 (cond (#t => 'ok))) ===> ok12001201The macro transformer for cond recognizes => as a local variable, and1202hence an expression, and not as the top-level identifier =>, which the1203macro transformer treats as a syntactic keyword. Thus the example1204expands into12051206 (let ((=> #f))1207 (if #t (begin => 'ok)))12081209instead of12101211 (let ((=> #f))1212 (let ((temp #t))1213 (if temp ('ok temp))))12141215which would result in an invalid procedure call.12161217==== Signaling errors in macro transformers12181219<macro>(syntax-error <message> <args> ...)</macro>12201221{{syntax-error}} behaves similarly to {{error}} except that implementations with1222an expansion pass separate from evaluation should signal an error as soon as1223{{syntax-error}} is expanded. This can be used as a syntax-rules <template> for a1224<pattern> that is an invalid use of the macro, which can provide more1225descriptive error messages. <message> is a string literal, and <args> arbitrary1226expressions providing additional information. Applications cannot count on1227being able to catch syntax errors with exception handlers or guards.12281229 (define-syntax simple-let1230 (syntax-rules ()1231 ((_ (head ... ((x . y) val) . tail)1232 body1 body2 ...)1233 (syntax-error1234 "expected an identifier but got"1235 (x . y)))1236 ((_ ((name val) ...) body1 body2 ...)1237 ((lambda (name ...) body1 body2 ...)1238 val ...))))123912401241== Program structure12421243=== Programs12441245A Scheme program consists of a sequence of expressions, definitions,1246and syntax definitions. Expressions are described in chapter 4;1247definitions and syntax definitions are the subject of the rest of the1248present chapter.12491250Programs are typically stored in files or entered interactively to a1251running Scheme system, although other paradigms are possible;1252questions of user interface lie outside the scope of this1253report. (Indeed, Scheme would still be useful as a notation for1254expressing computational methods even in the absence of a mechanical1255implementation.)12561257Definitions and syntax definitions occurring at the top level of a1258program can be interpreted declaratively. They cause bindings to be1259created in the top level environment or modify the value of existing1260top-level bindings. Expressions occurring at the top level of a1261program are interpreted imperatively; they are executed in order when1262the program is invoked or loaded, and typically perform some kind of1263initialization.12641265At the top level of a program (begin <form1> ...) is equivalent to the1266sequence of expressions, definitions, and syntax definitions that form1267the body of the begin.12681269=== Import declarations12701271<macro>(import IMPORT-SET ...)</macro>12721273An import declaration provides a way to import identifiers exported by a1274library. Each <import set> names a set of bindings from a library and possibly1275specifies local names for the imported bindings. It takes one of the following1276forms:12771278* <library name>12791280* {{(only <import set> <identifier> ...)}}12811282* {{(except <import set> <identifier> ...)}}12831284* {{(prefix <import set> <identifier>)}}12851286* {{(rename <import set> (<identifier[1]> <identifier[2]>) ...)}}12871288In the first form, all of the identifiers in the named library's export clauses1289are imported with the same names (or the exported names if exported with rename1290). The additional <import set> forms modify this set as follows:12911292* only produces a subset of the given <import set> including only the listed1293 identifiers (after any renaming). It is an error if any of the listed1294 identifiers are not found in the original set.12951296* except produces a subset of the given <import set>, excluding the listed1297 identifiers (after any renaming). It is an error if any of the listed1298 identifiers are not found in the original set.12991300* rename modifies the given <import set>, replacing each instance of1301 <identifier[1]> with <identifier[2]>. It is an error if any of the listed1302 <identifier[1]>s are not found in the original set.13031304* prefix automatically renames all identifiers in the given <import set>,1305 prefixing each with the specified <identifier>.13061307=== Definitions13081309Definitions are valid in some, but not all, contexts where expressions1310are allowed. They are valid only at the top level of a <program> and1311at the beginning of a <body>.13121313A definition should have one of the following forms:13141315<macro>(define <variable> <expression>)</macro><br>1316<macro>(define (<variable> <formals>) <body>)</macro><br>13171318<Formals> should be either a sequence of zero or more variables, or a1319sequence of one or more variables followed by a space-delimited period1320and another variable (as in a lambda expression). This form is1321equivalent to13221323 (define <variable>1324 (lambda (<formals>) <body>)).13251326<macro>(define <variable>)</macro>13271328This form is a CHICKEN extension to R7RS, and is equivalent to13291330 (define <variable> (void))13311332<macro>(define (<variable> . <formal>) <body>)</macro><br>13331334<Formal> should be a single variable. This form is equivalent to13351336 (define <variable>1337 (lambda <formal> <body>)).13381339<macro>(define ((<variable> <formal> ...) ...) <body>)</macro><br>13401341As an extension to R7RS, CHICKEN allows ''curried'' definitions, where1342the variable name may also be a list specifying a name and a nested1343lambda list. For example,13441345 (define ((make-adder x) y) (+ x y))13461347is equivalent to13481349 (define (make-adder x) (lambda (y) (+ x y))).13501351This type of curried definition can be nested arbitrarily and combined1352with dotted tail notation or DSSSL keywords.13531354==== Top level definitions13551356At the top level of a program, a definition13571358 (define <variable> <expression>)13591360has essentially the same effect as the assignment expression13611362 (set! <variable> <expression>)13631364if <variable> is bound. If <variable> is not bound, however, then the1365definition will bind <variable> to a new location before performing1366the assignment, whereas it would be an error to perform a set! on an1367unbound variable in standard Scheme. In CHICKEN, {{set!}} at toplevel1368has the same effect as a definition, unless inside a module, in which1369case it is an error.13701371 (define add31372 (lambda (x) (+ x 3)))1373 (add3 3) ===> 61374 (define first car)1375 (first '(1 2)) ===> 113761377Some implementations of Scheme use an initial environment in which all1378possible variables are bound to locations, most of which contain1379undefined values. Top level definitions in such an implementation are1380truly equivalent to assignments. In CHICKEN, attempting to evaluate1381an unbound identifier will result in an error, but you ''can'' use1382{{set!}} to bind an initial value to it.13831384==== Internal definitions13851386Definitions may occur at the beginning of a <body> (that is, the body1387of a lambda, let, let*, letrec, let-syntax, or letrec-syntax1388expression or that of a definition of an appropriate form). Such1389definitions are known as internal definitions as opposed to the top1390level definitions described above. The variable defined by an internal1391definition is local to the <body>. That is, <variable> is bound rather1392than assigned, and the region of the binding is the entire <body>. For1393example,13941395 (let ((x 5))1396 (define foo (lambda (y) (bar x y)))1397 (define bar (lambda (a b) (+ (* a b) a)))1398 (foo (+ x 3))) ===> 4513991400A <body> containing internal definitions can always be converted into1401a completely equivalent letrec expression. For example, the let1402expression in the above example is equivalent to14031404 (let ((x 5))1405 (letrec ((foo (lambda (y) (bar x y)))1406 (bar (lambda (a b) (+ (* a b) a))))1407 (foo (+ x 3))))14081409Just as for the equivalent letrec expression, it must be possible to1410evaluate each <expression> of every internal definition in a <body>1411without assigning or referring to the value of any <variable> being1412defined.14131414Wherever an internal definition may occur (begin <definition1> ...) is1415equivalent to the sequence of definitions that form the body of the1416begin.14171418CHICKEN extends the R7RS semantics by allowing internal definitions1419everywhere, and not only at the beginning of a body. A set of internal1420definitions is equivalent to a {{letrec}} form enclosing all following1421expressions in the body:14221423 (let ((foo 123))1424 (bar)1425 (define foo 456)1426 (baz foo) )14271428expands into14291430 (let ((foo 123))1431 (bar)1432 (letrec ((foo 456))1433 (baz foo) ) )14341435Local sequences of {{define-syntax}} forms are translated into1436equivalent {{letrec-syntax}} forms that enclose the following forms as1437the body of the expression.14381439=== Multiple-value definitions14401441Another kind of definition is provided by define-values, which creates multiple1442definitions from a single expression returning multiple values. It is allowed1443wherever define is allowed.14441445<macro>(define-values <formals> <expression>)</macro>14461447It is an error if a variable appears more than once in the set of <formals>.14481449Semantics: <Expression> is evaluated, and the <formals> are bound to the return1450values in the same way that the <formals> in a lambda expression are matched to1451the arguments in a procedure call.14521453 (define-values (x y) (exact-integer-sqrt 17))1454 (list x y) ==> (4 1)14551456 (let ()1457 (define-values (x y) (values 1 2))1458 (+ x y)) ==> 314591460=== Syntax definitions14611462Syntax definitions are valid only at the top level of a1463<program>. They have the following form:14641465<macro>(define-syntax <keyword> <transformer spec>)</macro>14661467{{<Keyword>}} is an identifier, and the {{<transformer spec>}} should1468be an instance of {{syntax-rules}}. Note that CHICKEN also supports1469{{er-macro-transformer}} and {{ir-macro-transformer}} here. For more1470information see [[Module (chicken syntax)|the (chicken syntax) module]].14711472The top-level syntactic environment is extended by binding the1473<keyword> to the specified transformer.14741475In standard Scheme, there is no define-syntax analogue of internal1476definitions in, but CHICKEN allows these as an extension to the1477standard. This means {{define-syntax}} may be used to define local1478macros that are visible throughout the rest of the body in which the1479definition occurred, i.e.14801481 (let ()1482 ...1483 (define-syntax foo ...)1484 (define-syntax bar ...)1485 ...)14861487is expanded into14881489 (let ()1490 ...1491 (letrec-syntax ((foo ...) (bar ...))1492 ...) )14931494{{syntax-rules}} supports [[http://srfi.schemers.org/srfi-46/|SRFI-46]]1495in allowing the ellipsis identifier to be user-defined by passing it as the first1496argument to the {{syntax-rules}} form. Also, "tail" patterns of the form14971498 (syntax-rules ()1499 ((_ (a b ... c)1500 ...15011502are supported.15031504The effect of destructively modifying the s-expression passed to a1505transformer procedure is undefined.15061507Although macros may expand into definitions and syntax definitions in1508any context that permits them, it is an error for a definition or1509syntax definition to shadow a syntactic keyword whose meaning is1510needed to determine whether some form in the group of forms that1511contains the shadowing definition is in fact a definition, or, for1512internal definitions, is needed to determine the boundary between the1513group and the expressions that follow the group. For example, the1514following are errors:15151516 (define define 3)15171518 (begin (define begin list))15191520 (let-syntax1521 ((foo (syntax-rules ()1522 ((foo (proc args ...) body ...)1523 (define proc1524 (lambda (args ...)1525 body ...))))))1526 (let ((x 3))1527 (foo (plus x y) (+ x y))1528 (define foo x)1529 (plus foo x)))15301531=== Record-type definitions15321533Record-type definitions are used to introduce new data types, called record1534types. Like other definitions, they can appear either at the outermost level or1535in a body. The values of a record type are called records and are aggregations1536of zero or more fields, each of which holds a single location. A predicate, a1537constructor, and field accessors and mutators are defined for each record type.15381539<macro>(define-record-type <name> <constructor> <pred> <field> ...)</macro>15401541Syntax: <name> and <pred> are identifiers. The <constructor> is of the form1542{{(<constructor name> <field name> ...)}} and each <field> is either of the form1543{{(<field name> <accessor name>)}} or of the form {{(<field name> <accessor name> <modifier name>)}}. It is an error for the same identifier to occur more than once1544as a field name. It is also an error for the same identifier to occur more than1545once as an accessor or mutator name.15461547The define-record-type construct is generative: each use creates a new record1548type that is distinct from all existing types, including Scheme's predefined1549types and other record types — even record types of the same name or structure.15501551An instance of define-record-type is equivalent to the following definitions:15521553* <name> is bound to a representation of the record type itself. This may be1554 a run-time object or a purely syntactic representation. The representation1555 is not utilized in this report, but it serves as a means to identify the1556 record type for use by further language extensions.15571558* <constructor name> is bound to a procedure that takes as many arguments as1559 there are <field name>s in the {{(<constructor name> ...)}} subexpression and1560 returns a new record of type <name>. Fields whose names are listed with1561 <constructor name> have the corresponding argument as their initial value.1562 The initial values of all other fields are unspecified. It is an error for1563 a field name to appear in <constructor> but not as a <field name>.15641565* <pred> is bound to a predicate that returns #t when given a value returned1566 by the procedure bound to <constructor name> and #f for everything else.15671568* Each <accessor name> is bound to a procedure that takes a record of type1569 <name> and returns the current value of the corresponding field. It is an1570 error to pass an accessor a value which is not a record of the appropriate1571 type.15721573* Each <modifier name> is bound to a procedure that takes a record of type1574 <name> and a value which becomes the new value of the corresponding field;1575 an unspecified value is returned. It is an error to pass a modifier a first1576 argument which is not a record of the appropriate type.15771578For instance, the following record-type definition15791580 (define-record-type <pare>1581 (kons x y)1582 pare?1583 (x kar set-kar!)1584 (y kdr))15851586defines kons to be a constructor, kar and kdr to be accessors, set-kar! to be a1587modifier, and pare? to be a predicate for instances of <pare>.15881589 (pare? (kons 1 2)) ===> #t1590 (pare? (cons 1 2)) ===> #f1591 (kar (kons 1 2)) ===> 11592 (kdr (kons 1 2)) ===> 21593 (let ((k (kons 1 2)))1594 (set-kar! k 3)1595 (kar k)) ===> 315961597As an extension the <modifier name> may have the form1598{{(setter PROCEDURE)}}, which will define a SRFI-17 setter-procedure1599for the given {{PROCEDURE}} that sets the field value.1600Usually {{PROCEDURE}} has the same name is <accessor name> (but it1601doesn't have to).16021603=== Libraries16041605Libraries provide a way to organize Scheme programs into reusable parts with1606explicitly defined interfaces to the rest of the program. This section defines1607the notation and semantics for libraries.16081609==== Library Syntax16101611A library definition takes the following form:16121613<macro>(define-library <library name> <library declaration> ...)</macro>16141615<library name> is a list whose members are identifiers and exact non-negative1616integers. It is used to identify the library uniquely when importing from other1617programs or libraries. Libraries whose first identifier is scheme are reserved1618for use by this report and future versions of this report. Libraries whose1619first identifier is srfi are reserved for libraries implementing Scheme1620Requests for Implementation. It is inadvisable, but not an error, for1621identifiers in library names to contain any of the characters | \ ? * < " : > +1622[ ] / or control characters after escapes are expanded.16231624A <library declaration> is any of:16251626* {{(export <export spec> ...)}}16271628* {{(export-all)}}16291630* {{(import <import set> ...)}}16311632* {{(begin <command or definition> ...)}}16331634* {{(include <filename[1]> <filename[2]> ...)}}16351636* {{(include-ci <filename[1]> <filename[2]> ...)}}16371638* {{(include-library-declarations <filename[1]> <filename[2]> ...)}}16391640* {{(cond-expand <ce-clause[1]> <ce-clause[2]> ...}}16411642An export declaration specifies a list of identifiers which can be made visible1643to other libraries or programs. An <export spec> takes one of the following1644forms:16451646* <identifier>16471648* {{(rename <identifier[1]> <identifier[2]>)}}16491650In an <export spec>, an <identifier> names a single binding defined within or1651imported into the library, where the external name for the export is the same1652as the name of the binding within the library. A {{rename}} spec exports the1653binding defined within or imported into the library and named by <identifier1654[1]> in each {{(<identifier[1]> <identifier[2]>)}} pairing, using <identifier[2]>1655as the external name.16561657As an extension to R7RS, CHICKEN allows the {{(export-all)}} specifier,1658which exports all defined entities to be visible when importing the1659library.16601661An import declaration provides a way to import the identifiers exported by1662another library.16631664The {{begin}}, {{include}}, and {{include}}-ci declarations are used to specify the body of1665the library. They have the same syntax and semantics as the corresponding1666expression types. This form of begin is analogous to, but not the same as, the1667two types of begin defined in section 4.2.3.16681669The {{include-library-declarations}} declaration is similar to {{include}} except that1670the contents of the file are spliced directly into the current library1671definition. This can be used, for example, to share the same export declaration1672among multiple libraries as a simple form of library interface.16731674The {{cond-expand}} declaration has the same syntax and semantics as the1675{{cond-expand}} expression type, except that it expands to spliced-in library1676declarations rather than expressions enclosed in begin.16771678One possible implementation of libraries is as follows: After all {{cond-expand}}1679library declarations are expanded, a new environment is constructed for the1680library consisting of all imported bindings. The expressions from all begin,1681{{include}} and {{include-ci}} library declarations are expanded in that environment in1682the order in which they occur in the library. Alternatively, {{cond-expand}} and1683{{import}} declarations may be processed in left to right order interspersed with1684the processing of other declarations, with the environment growing as imported1685bindings are added to it by each import declaration.16861687When a library is loaded, its expressions are executed in textual order. If a1688library's definitions are referenced in the expanded form of a program or1689library body, then that library must be loaded before the expanded program or1690library body is evaluated. This rule applies transitively. If a library is1691imported by more than one program or library, it may possibly be loaded1692additional times.16931694Similarly, during the expansion of a library (foo), if any syntax keywords1695imported from another library (bar) are needed to expand the library, then the1696library (bar) must be expanded and its syntax definitions evaluated before the1697expansion of (foo).169816991700== Standard procedures17011702This chapter describes Scheme's built-in procedures. The initial (or1703"top level") Scheme environment starts out with a number of variables1704bound to locations containing useful values, most of which are1705primitive procedures that manipulate data. For example, the variable1706abs is bound to (a location initially containing) a procedure of one1707argument that computes the absolute value of a number, and the variable1708+ is bound to a procedure that computes sums. Built-in procedures that1709can easily be written in terms of other built-in procedures are1710identified as "library procedures".17111712A program may use a top-level definition to bind any variable. It may1713subsequently alter any such binding by an assignment (see1714[[#assignments|assignments]], above). These operations do1715not modify the behavior of Scheme's built-in procedures. Altering any1716top-level binding that has not been introduced by a definition has an1717unspecified effect on the behavior of the built-in procedures.17181719=== Equivalence predicates17201721A predicate is a procedure that always returns a boolean value (#t or #f).1722An equivalence predicate is the computational analogue of a1723mathematical equivalence relation (it is symmetric, reflexive, and1724transitive). Of the equivalence predicates described in this section,1725eq? is the finest or most discriminating, and equal? is the coarsest.1726eqv? is slightly less discriminating than eq?.17271728<procedure>(eqv? obj[1] obj[2])</procedure><br>17291730The eqv? procedure defines a useful equivalence relation on objects.1731Briefly, it returns #t if obj[1] and obj[2] should normally be regarded1732as the same object. This relation is left slightly open to1733interpretation, but the following partial specification of eqv? holds1734for all implementations of Scheme.17351736The eqv? procedure returns #t if:17371738* obj[1] and obj[2] are both #t or both #f.17391740* obj[1] and obj[2] are both symbols and17411742 (string=? (symbol->string obj1)1743 (symbol->string obj2))1744 ===> #t17451746Note: This assumes that neither obj[1] nor obj[2] is an "uninterned1747symbol" as alluded to in the section on [[#symbols|symbols]]. This1748report does not presume to specify the behavior of eqv? on1749implementation-dependent extensions.17501751* obj[1] and obj[2] are both numbers, are numerically equal (see =,1752 under [[#numerical-operations|numerical operations]]), and are1753 either both exact or both inexact.17541755* obj[1] and obj[2] are both characters and are the same character1756 according to the char=? procedure (see "[[#characters|characters]]").17571758* both obj[1] and obj[2] are the empty list.17591760* obj[1] and obj[2] are pairs, vectors, or strings that denote the1761 same locations in the store.17621763* obj[1] and obj[2] are procedures whose location tags are equal1764 (see "[[#procedures|procedures]]").17651766The eqv? procedure returns #f if:17671768* obj[1] and obj[2] are of different types.17691770* one of obj[1] and obj[2] is #t but the other is #f.17711772* obj[1] and obj[2] are symbols but17731774 (string=? (symbol->string obj[1])1775 (symbol->string obj[2]))1776 ===> #f17771778* one of obj[1] and obj[2] is an exact number but the other is an1779 inexact number.17801781* obj[1] and obj[2] are numbers for which the = procedure returns #f.17821783* obj[1] and obj[2] are characters for which the char=? procedure1784 returns #f.17851786* one of obj[1] and obj[2] is the empty list but the other is not.17871788* obj[1] and obj[2] are pairs, vectors, or strings that denote1789 distinct locations.17901791* obj[1] and obj[2] are procedures that would behave differently1792 (return different value(s) or have different side effects) for some1793 arguments.17941795 (eqv? 'a 'a) ===> #t1796 (eqv? 'a 'b) ===> #f1797 (eqv? 2 2) ===> #t1798 (eqv? '() '()) ===> #t1799 (eqv? 100000000 100000000) ===> #t1800 (eqv? (cons 1 2) (cons 1 2)) ===> #f1801 (eqv? (lambda () 1)1802 (lambda () 2)) ===> #f1803 (eqv? #f 'nil) ===> #f1804 (let ((p (lambda (x) x)))1805 (eqv? p p)) ===> #t18061807The following examples illustrate cases in which the above rules do not1808fully specify the behavior of eqv?. All that can be said about such1809cases is that the value returned by eqv? must be a boolean.18101811 (eqv? "" "") ===> unspecified1812 (eqv? '#() '#()) ===> unspecified1813 (eqv? (lambda (x) x)1814 (lambda (x) x)) ===> unspecified1815 (eqv? (lambda (x) x)1816 (lambda (y) y)) ===> unspecified18171818The next set of examples shows the use of eqv? with procedures that1819have local state. Gen-counter must return a distinct procedure every1820time, since each procedure has its own internal counter. Gen-loser,1821however, returns equivalent procedures each time, since the local state1822does not affect the value or side effects of the procedures.18231824 (define gen-counter1825 (lambda ()1826 (let ((n 0))1827 (lambda () (set! n (+ n 1)) n))))1828 (let ((g (gen-counter)))1829 (eqv? g g)) ===> #t1830 (eqv? (gen-counter) (gen-counter))1831 ===> #f1832 (define gen-loser1833 (lambda ()1834 (let ((n 0))1835 (lambda () (set! n (+ n 1)) 27))))1836 (let ((g (gen-loser)))1837 (eqv? g g)) ===> #t1838 (eqv? (gen-loser) (gen-loser))1839 ===> unspecified18401841 (letrec ((f (lambda () (if (eqv? f g) 'both 'f)))1842 (g (lambda () (if (eqv? f g) 'both 'g))))1843 (eqv? f g))1844 ===> unspecified18451846 (letrec ((f (lambda () (if (eqv? f g) 'f 'both)))1847 (g (lambda () (if (eqv? f g) 'g 'both))))1848 (eqv? f g))1849 ===> #f18501851Since it is an error to modify constant objects (those returned by1852literal expressions), implementations are permitted, though not1853required, to share structure between constants where appropriate. Thus1854the value of eqv? on constants is sometimes implementation-dependent.18551856 (eqv? '(a) '(a)) ===> unspecified1857 (eqv? "a" "a") ===> unspecified1858 (eqv? '(b) (cdr '(a b))) ===> unspecified1859 (let ((x '(a)))1860 (eqv? x x)) ===> #t18611862Rationale: The above definition of eqv? allows implementations1863latitude in their treatment of procedures and literals:1864implementations are free either to detect or to fail to detect that1865two procedures or two literals are equivalent to each other, and1866can decide whether or not to merge representations of equivalent1867objects by using the same pointer or bit pattern to represent both.18681869<procedure>(eq? obj[1] obj[2])</procedure><br>18701871Eq? is similar to eqv? except that in some cases it is capable of1872discerning distinctions finer than those detectable by eqv?.18731874Eq? and eqv? are guaranteed to have the same behavior on symbols,1875booleans, the empty list, pairs, procedures, and non-empty strings and1876vectors. Eq?'s behavior on numbers and characters is1877implementation-dependent, but it will always return either true or1878false, and will return true only when eqv? would also return true. Eq?1879may also behave differently from eqv? on empty vectors and empty1880strings.18811882 (eq? 'a 'a) ===> #t1883 (eq? '(a) '(a)) ===> unspecified1884 (eq? (list 'a) (list 'a)) ===> #f1885 (eq? "a" "a") ===> unspecified1886 (eq? "" "") ===> unspecified1887 (eq? '() '()) ===> #t1888 (eq? 2 2) ===> unspecified1889 (eq? #\A #\A) ===> unspecified1890 (eq? car car) ===> #t1891 (let ((n (+ 2 3)))1892 (eq? n n)) ===> unspecified1893 (let ((x '(a)))1894 (eq? x x)) ===> #t1895 (let ((x '#()))1896 (eq? x x)) ===> #t1897 (let ((p (lambda (x) x)))1898 (eq? p p)) ===> #t18991900Rationale: It will usually be possible to implement eq? much more1901efficiently than eqv?, for example, as a simple pointer comparison1902instead of as some more complicated operation. One reason is that1903it may not be possible to compute eqv? of two numbers in constant1904time, whereas eq? implemented as pointer comparison will always1905finish in constant time. Eq? may be used like eqv? in applications1906using procedures to implement objects with state since it obeys the1907same constraints as eqv?.19081909<procedure>(equal? obj[1] obj[2])</procedure><br>19101911Equal? recursively compares the contents of pairs, vectors, and1912strings, applying eqv? on other objects such as numbers and symbols. A1913rule of thumb is that objects are generally equal? if they print the1914same. Equal? may fail to terminate if its arguments are circular data1915structures.19161917 (equal? 'a 'a) ===> #t1918 (equal? '(a) '(a)) ===> #t1919 (equal? '(a (b) c)1920 '(a (b) c)) ===> #t1921 (equal? "abc" "abc") ===> #t1922 (equal? 2 2) ===> #t1923 (equal? (make-vector 5 'a)1924 (make-vector 5 'a)) ===> #t1925 (equal? (lambda (x) x)1926 (lambda (y) y)) ===> unspecified19271928=== Numbers19291930Numerical computation has traditionally been neglected by the Lisp1931community. Until Common Lisp there was no carefully thought out1932strategy for organizing numerical computation, and with the exception1933of the MacLisp system [20] little effort was made to execute numerical1934code efficiently. This report recognizes the excellent work of the1935Common Lisp committee and accepts many of their recommendations. In1936some ways this report simplifies and generalizes their proposals in a1937manner consistent with the purposes of Scheme.19381939It is important to distinguish between the mathematical numbers, the1940Scheme numbers that attempt to model them, the machine representations1941used to implement the Scheme numbers, and notations used to write1942numbers. This report uses the types number, complex, real, rational,1943and integer to refer to both mathematical numbers and Scheme numbers.1944Machine representations such as fixed point and floating point are1945referred to by names such as fixnum and flonum.19461947==== Numerical types19481949Mathematically, numbers may be arranged into a tower of subtypes in1950which each level is a subset of the level above it:19511952 number1953 complex1954 real1955 rational1956 integer19571958For example, 3 is an integer. Therefore 3 is also a rational, a real,1959and a complex. The same is true of the Scheme numbers that model 3. For1960Scheme numbers, these types are defined by the predicates number?,1961complex?, real?, rational?, and integer?.19621963There is no simple relationship between a number's type and its1964representation inside a computer. Although most implementations of1965Scheme will offer at least two different representations of 3, these1966different representations denote the same integer.19671968Scheme's numerical operations treat numbers as abstract data, as1969independent of their representation as possible. Although an1970implementation of Scheme may use fixnum, flonum, and perhaps other1971representations for numbers, this should not be apparent to a casual1972programmer writing simple programs.19731974It is necessary, however, to distinguish between numbers that are1975represented exactly and those that may not be. For example, indexes1976into data structures must be known exactly, as must some polynomial1977coefficients in a symbolic algebra system. On the other hand, the1978results of measurements are inherently inexact, and irrational numbers1979may be approximated by rational and therefore inexact approximations.1980In order to catch uses of inexact numbers where exact numbers are1981required, Scheme explicitly distinguishes exact from inexact numbers.1982This distinction is orthogonal to the dimension of type.19831984==== Exactness19851986Scheme numbers are either exact or inexact. A number is exact if it was1987written as an exact constant or was derived from exact numbers using1988only exact operations. A number is inexact if it was written as an1989inexact constant, if it was derived using inexact ingredients, or if it1990was derived using inexact operations. Thus inexactness is a contagious1991property of a number. If two implementations produce exact results for1992a computation that did not involve inexact intermediate results, the1993two ultimate results will be mathematically equivalent. This is1994generally not true of computations involving inexact numbers since1995approximate methods such as floating point arithmetic may be used, but1996it is the duty of each implementation to make the result as close as1997practical to the mathematically ideal result.19981999Rational operations such as + should always produce exact results when2000given exact arguments. If the operation is unable to produce an exact2001result, then it may either report the violation of an implementation2002restriction or it may silently coerce its result to an inexact value.2003See [[#implementation-restrictions|the next section]].20042005With the exception of inexact->exact, the operations described in this2006section must generally return inexact results when given any inexact2007arguments. An operation may, however, return an exact result if it can2008prove that the value of the result is unaffected by the inexactness of2009its arguments. For example, multiplication of any number by an exact2010zero may produce an exact zero result, even if the other argument is2011inexact.20122013==== Implementation restrictions20142015Implementations of Scheme are not required to implement the whole2016tower of subtypes given under "[[#Numerical types|Numerical types]]",2017but they must implement a coherent subset consistent with both the2018purposes of the implementation and the spirit of the Scheme2019language. For example, an implementation in which all numbers are real2020may still be quite useful.20212022Implementations may also support only a limited range of numbers of any2023type, subject to the requirements of this section. The supported range2024for exact numbers of any type may be different from the supported range2025for inexact numbers of that type. For example, an implementation that2026uses flonums to represent all its inexact real numbers may support a2027practically unbounded range of exact integers and rationals while2028limiting the range of inexact reals (and therefore the range of inexact2029integers and rationals) to the dynamic range of the flonum format.2030Furthermore the gaps between the representable inexact integers and2031rationals are likely to be very large in such an implementation as the2032limits of this range are approached.20332034An implementation of Scheme must support exact integers throughout the2035range of numbers that may be used for indexes of lists, vectors, and2036strings or that may result from computing the length of a list, vector,2037or string. The length, vector-length, and string-length procedures must2038return an exact integer, and it is an error to use anything but an2039exact integer as an index. Furthermore any integer constant within the2040index range, if expressed by an exact integer syntax, will indeed be2041read as an exact integer, regardless of any implementation restrictions2042that may apply outside this range. Finally, the procedures listed below2043will always return an exact integer result provided all their arguments2044are exact integers and the mathematically expected result is2045representable as an exact integer within the implementation:20462047 - *2048 + abs2049 ceiling denominator2050 exact-integer-sqrt expt2051 floor floor/2052 floor-quotient floor-remainder2053 gcd lcm2054 max min2055 modulo numerator2056 quotient rationalize2057 remainder round2058 square truncate2059 truncate/ truncate-quotient2060 truncate-remainder20612062CHICKEN follows the IEEE 32-bit and 64-bit floating point2063standards on all supported platforms.20642065It is the programmer's responsibility to avoid using inexact number objects2066with magnitude or significand too large to be represented in the2067implementation.20682069In addition, implementations may distinguish special numbers called positive2070infinity, negative infinity, NaN, and negative zero.20712072Positive infinity is regarded as an inexact real (but not rational) number that2073represents an indeterminate value greater than the numbers represented by all2074rational numbers. Negative infinity is regarded as an inexact real (but not2075rational) number that represents an indeterminate value less than the numbers2076represented by all rational numbers.20772078Adding or multiplying an infinite value by any finite real value results in an2079appropriately signed infinity; however, the sum of positive and negative2080infinities is a NaN. Positive infinity is the reciprocal of zero, and negative2081infinity is the reciprocal of negative zero. The behavior of the transcendental2082functions is sensitive to infinity in accordance with IEEE 754.20832084A NaN is regarded as an inexact real (but not rational) number so indeterminate2085that it might represent any real value, including positive or negative2086infinity, and might even be greater than positive infinity or less than2087negative infinity. An implementation that does not support non-real numbers may2088use NaN to represent non-real values like (sqrt -1.0) and (asin 2.0).20892090A NaN always compares false to any number, including a NaN. An arithmetic2091operation where one operand is NaN returns NaN, unless the implementation can2092prove that the result would be the same if the NaN were replaced by any2093rational number. Dividing zero by zero results in NaN unless both zeros are2094exact.20952096Negative zero is an inexact real value written -0.0 and is distinct (in the2097sense of eqv?) from 0.0. A Scheme implementation is not required to distinguish2098negative zero. If it does, however, the behavior of the transcendental2099functions is sensitive to the distinction in accordance with IEEE 754.2100Specifically, in a Scheme implementing both complex numbers and negative zero,2101the branch cut of the complex logarithm function is such that (imag-part (log2102-1.0-0.0i)) is --π rather than π.21032104Furthermore, the negation of negative zero is ordinary zero and vice versa.2105This implies that the sum of two or more negative zeros is negative, and the2106result of subtracting (positive) zero from a negative zero is likewise2107negative. However, numerical comparisons treat negative zero as equal to zero.21082109Note that both the real and the imaginary parts of a complex number can be2110infinities, NaNs, or negative zero.211121122113==== Syntax of numerical constants21142115For a complete formal description of the syntax of the written2116representations for numbers, see the R7RS report. Note that case is2117not significant in numerical constants.21182119A number may be written in binary, octal, decimal, or hexadecimal by2120the use of a radix prefix. The radix prefixes are #b (binary), #o2121(octal), #d (decimal), and #x (hexadecimal). With no radix prefix, a2122number is assumed to be expressed in decimal.21232124A numerical constant may be specified to be either exact or inexact by2125a prefix. The prefixes are #e for exact, and #i for inexact. An2126exactness prefix may appear before or after any radix prefix that is2127used. If the written representation of a number has no exactness2128prefix, the constant may be either inexact or exact. It is inexact if2129it contains a decimal point, an exponent, or a "#" character in the2130place of a digit, otherwise it is exact. In systems with inexact2131numbers of varying precisions it may be useful to specify the precision2132of a constant. For this purpose, numerical constants may be written2133with an exponent marker that indicates the desired precision of the2134inexact representation. The letters s, f, d, and l specify the use of2135short, single, double, and long precision, respectively. (When fewer2136than four internal inexact representations exist, the four size2137specifications are mapped onto those available. For example, an2138implementation with two internal representations may map short and2139single together and long and double together.) In addition, the2140exponent marker e specifies the default precision for the2141implementation. The default precision has at least as much precision as2142double, but implementations may wish to allow this default to be set by2143the user.21442145 3.14159265358979F02146 Round to single --- 3.1415932147 0.6L02148 Extend to long --- .60000000000000021492150==== Numerical operations21512152The numerical routines described below have argument restrictions,2153which are encoded in the naming conventions of the arguments as2154given in the procedure's signature. The conventions are as follows:21552156; {{obj}} : any object2157; {{list, list1, ... listj, ... list}} : (see "[[#pairs-and-lists|Pairs and lists]]" below)2158; {{z, z1, ... zj, ...}} : complex number2159; {{x, x1, ... xj, ...}} : real number2160; {{y, y1, ... yj, ...}} : real number2161; {{q, q1, ... qj, ...}} : rational number2162; {{n, n1, ... nj, ...}} : integer2163; {{k, k1, ... kj, ...}} : exact non-negative integer21642165The examples used in this section assume that any2166numerical constant written using an exact notation is indeed2167represented as an exact number. Some examples also assume that certain2168numerical constants written using an inexact notation can be2169represented without loss of accuracy; the inexact constants were chosen2170so that this is likely to be true in implementations that use flonums2171to represent inexact numbers.21722173<procedure>(number? obj)</procedure><br>2174<procedure>(complex? obj)</procedure><br>2175<procedure>(real? obj)</procedure><br>2176<procedure>(rational? obj)</procedure><br>2177<procedure>(integer? obj)</procedure><br>21782179These numerical type predicates can be applied to any kind of argument,2180including non-numbers. They return #t if the object is of the named2181type, and otherwise they return #f. In general, if a type predicate is2182true of a number then all higher type predicates are also true of that2183number. Consequently, if a type predicate is false of a number, then2184all lower type predicates are also false of that number. If z is an2185inexact complex number, then (real? z) is true if and only if (zero?2186(imag-part z)) is true. If x is an inexact real number, then (integer?2187x) is true if and only if (= x (round x)).21882189 (complex? 3+4i) ===> #t2190 (complex? 3) ===> #t2191 (real? 3) ===> #t2192 (real? -2.5+0.0i) ===> #t2193 (real? #e1e10) ===> #t2194 (rational? 6/10) ===> #t2195 (rational? 6/3) ===> #t2196 (integer? 3+0i) ===> #t2197 (integer? 3.0) ===> #t2198 (integer? 8/4) ===> #t21992200Note: The behavior of these type predicates on inexact numbers is2201unreliable, since any inaccuracy may affect the result.22022203Note: In many implementations the rational? procedure will be the2204same as real?, and the complex? procedure will be the same as2205number?, but unusual implementations may be able to represent some2206irrational numbers exactly or may extend the number system to2207support some kind of non-complex numbers.22082209<procedure>(exact? z)</procedure><br>2210<procedure>(inexact? z)</procedure><br>22112212These numerical predicates provide tests for the exactness of a2213quantity. For any Scheme number, precisely one of these predicates is2214true.22152216<procedure>(exact-integer? z)</procedure>22172218Returns #t if z is both exact and an integer; otherwise returns #f.22192220 (exact-integer? 32) ===> #t2221 (exact-integer? 32.0) ===> #f2222 (exact-integer? 32/5) ===> #f22232224<procedure>(= z[1] z[2] z[3] ...)</procedure><br>2225<procedure>(< x[1] x[2] x[3] ...)</procedure><br>2226<procedure>(> x[1] x[2] x[3] ...)</procedure><br>2227<procedure>(<= x[1] x[2] x[3] ...)</procedure><br>2228<procedure>(>= x[1] x[2] x[3] ...)</procedure><br>22292230These procedures return #t if their arguments are (respectively):2231equal, monotonically increasing, monotonically decreasing,2232monotonically nondecreasing, or monotonically nonincreasing.22332234These predicates are required to be transitive.22352236Note: The traditional implementations of these predicates in2237Lisp-like languages are not transitive.22382239Note: While it is not an error to compare inexact numbers using2240these predicates, the results may be unreliable because a small2241inaccuracy may affect the result; this is especially true of = and2242zero?. When in doubt, consult a numerical analyst.22432244<procedure>(zero? z)</procedure><br>2245<procedure>(positive? x)</procedure><br>2246<procedure>(negative? x)</procedure><br>2247<procedure>(odd? n)</procedure><br>2248<procedure>(even? n)</procedure><br>22492250These numerical predicates test a number for a particular property,2251returning #t or #f. See note above.22522253<procedure>(max x[1] x[2] ...)</procedure><br>2254<procedure>(min x[1] x[2] ...)</procedure><br>22552256These procedures return the maximum or minimum of their arguments.22572258 (max 3 4) ===> 4 ; exact2259 (max 3.9 4) ===> 4.0 ; inexact22602261Note: If any argument is inexact, then the result will also be2262inexact (unless the procedure can prove that the inaccuracy is not2263large enough to affect the result, which is possible only in2264unusual implementations). If min or max is used to compare numbers2265of mixed exactness, and the numerical value of the result cannot be2266represented as an inexact number without loss of accuracy, then the2267procedure may report a violation of an implementation restriction.22682269<procedure>(+ z[1] ...)</procedure><br>2270<procedure>(* z[1] ...)</procedure><br>22712272These procedures return the sum or product of their arguments.22732274 (+ 3 4) ===> 72275 (+ 3) ===> 32276 (+) ===> 02277 (* 4) ===> 42278 (*) ===> 122792280<procedure>(- z[1] z[2])</procedure><br>2281<procedure>(- z)</procedure><br>2282<procedure>(- z[1] z[2] ...)</procedure><br>2283<procedure>(/ z[1] z[2])</procedure><br>2284<procedure>(/ z)</procedure><br>2285<procedure>(/ z[1] z[2] ...)</procedure><br>22862287With two or more arguments, these procedures return the difference or2288quotient of their arguments, associating to the left. With one2289argument, however, they return the additive or multiplicative inverse2290of their argument.22912292 (- 3 4) ===> -12293 (- 3 4 5) ===> -62294 (- 3) ===> -32295 (/ 3 4 5) ===> 3/202296 (/ 3) ===> 1/322972298<procedure>(abs x)</procedure><br>22992300Abs returns the absolute value of its argument.23012302 (abs -7) ===> 723032304<procedure>(floor/ n[1] n[2])</procedure><br>2305<procedure>(floor-quotient n[1] n[2])</procedure><br>2306<procedure>(floor-remainder n[1] n[2])</procedure><br>2307<procedure>(truncate/ n[1] n[2])</procedure><br>2308<procedure>(truncate-quotient n[1] n[2])</procedure><br>2309<procedure>(truncate-remainder n[1] n[2])</procedure><br>23102311These procedures implement number-theoretic (integer) division. It is an error2312if n[2] is zero. The procedures ending in / return two integers; the other2313procedures return an integer. All the procedures compute a quotient n[q] and remainder2314n[r] such that n[1] = n[2] * n[q] + n[r]. For each of the division operators, there are three procedures defined as2315follows:23162317 (<operator>/ n[1] n[2]) ==> n[q] n[r]2318 (<operator>-quotient n[1] n[2]) ==> n[q]2319 (<operator>-remainder n[1] n[2]) ==> n[r]23202321The remainder n[r] is determined by the choice of integer n[q]: n[r] = n[1] -- n[2] * n[q]. Each set of operators uses a different choice of n[q]:23222323 floor n[q] = ⌊n[1] / n[2]⌋2324 truncate n[q] = runcate(n[1] / n[2])23252326For any of the operators, and for integers n[1] and n[2] with n[2] not equal to 0,23272328 (= n[1] (+ (* n[2] (<operator>-quotient n[1] n[2]))2329 (<operator>-remainder n[1] n[2])))2330 ==> #t23312332provided all numbers involved in that computation are exact.23332334Examples:23352336 (floor/ 5 2) ==> 2 12337 (floor/ -5 2) ==> -3 12338 (floor/ 5 -2) ==> -3 -12339 (floor/ -5 -2) ==> 2 -12340 (truncate/ 5 2) ==> 2 12341 (truncate/ -5 2) ==> -2 -12342 (truncate/ 5 -2) ==> -2 12343 (truncate/ -5 -2) ==> 2 -12344 (truncate/ -5.0 -2) ==> 2.0 -1.023452346<procedure>(quotient n[1] n[2])</procedure><br>2347<procedure>(remainder n[1] n[2])</procedure><br>2348<procedure>(modulo n[1] n[2])</procedure><br>23492350These procedures implement number-theoretic (integer) division. n[2]2351should be non-zero. All three procedures return integers. If n[1]/n[2]2352is an integer:23532354 (quotient n[1] n[2]) ===> n[1]/n[2]2355 (remainder n[1] n[2]) ===> 02356 (modulo n[1] n[2]) ===> 023572358If n[1]/n[2] is not an integer:23592360 (quotient n[1] n[2]) ===> n[q]2361 (remainder n[1] n[2]) ===> n[r]2362 (modulo n[1] n[2]) ===> n[m]23632364where n[q] is n[1]/n[2] rounded towards zero, 0 < |n[r]| < |n[2]|, 0 <2365|n[m]| < |n[2]|, n[r] and n[m] differ from n[1] by a multiple of n[2],2366n[r] has the same sign as n[1], and n[m] has the same sign as n[2].23672368From this we can conclude that for integers n[1] and n[2] with n[2] not2369equal to 0,23702371 (= n[1] (+ (* n[2] (quotient n[1] n[2]))2372 (remainder n[1] n[2])))2373 ===> #t23742375provided all numbers involved in that computation are exact.23762377 (modulo 13 4) ===> 12378 (remainder 13 4) ===> 123792380 (modulo -13 4) ===> 32381 (remainder -13 4) ===> -123822383 (modulo 13 -4) ===> -32384 (remainder 13 -4) ===> 123852386 (modulo -13 -4) ===> -12387 (remainder -13 -4) ===> -123882389 (remainder -13 -4.0) ===> -1.0 ; inexact23902391<procedure>(gcd n[1] ...)</procedure><br>2392<procedure>(lcm n[1] ...)</procedure><br>23932394These procedures return the greatest common divisor or least common2395multiple of their arguments. The result is always non-negative.23962397 (gcd 32 -36) ===> 42398 (gcd) ===> 02399 (lcm 32 -36) ===> 2882400 (lcm 32.0 -36) ===> 288.0 ; inexact2401 (lcm) ===> 124022403<procedure>(numerator q)</procedure><br>2404<procedure>(denominator q)</procedure><br>24052406These procedures return the numerator or denominator of their argument;2407the result is computed as if the argument was represented as a fraction2408in lowest terms. The denominator is always positive. The denominator of24090 is defined to be 1.24102411 (numerator (/ 6 4)) ===> 32412 (denominator (/ 6 4)) ===> 22413 (denominator2414 (exact->inexact (/ 6 4))) ===> 2.024152416<procedure>(floor x)</procedure><br>2417<procedure>(ceiling x)</procedure><br>2418<procedure>(truncate x)</procedure><br>2419<procedure>(round x)</procedure><br>24202421These procedures return integers. Floor returns the largest integer not2422larger than x. Ceiling returns the smallest integer not smaller than x.2423Truncate returns the integer closest to x whose absolute value is not2424larger than the absolute value of x. Round returns the closest integer2425to x, rounding to even when x is halfway between two integers.24262427Rationale: Round rounds to even for consistency with the default2428rounding mode specified by the IEEE floating point standard.24292430Note: If the argument to one of these procedures is inexact, then2431the result will also be inexact. If an exact value is needed, the2432result should be passed to the inexact->exact procedure.24332434 (floor -4.3) ===> -5.02435 (ceiling -4.3) ===> -4.02436 (truncate -4.3) ===> -4.02437 (round -4.3) ===> -4.024382439 (floor 3.5) ===> 3.02440 (ceiling 3.5) ===> 4.02441 (truncate 3.5) ===> 3.02442 (round 3.5) ===> 4.0 ; inexact24432444 (round 7/2) ===> 4 ; exact2445 (round 7) ===> 724462447<procedure>(rationalize x y)</procedure><br>24482449Rationalize returns the simplest rational number differing from x by no2450more than y. A rational number r[1] is simpler than another rational2451number r[2] if r[1] = p[1]/q[1] and r[2] = p[2]/q[2] (in lowest terms)2452and |p[1]| < |p[2]| and |q[1]| < |q[2]|. Thus 3/5 is simpler than 4/7.2453Although not all rationals are comparable in this ordering (consider 2/24547 and 3/5) any interval contains a rational number that is simpler than2455every other rational number in that interval (the simpler 2/5 lies2456between 2/7 and 3/5). Note that 0 = 0/1 is the simplest rational of2457all.24582459 (rationalize2460 (inexact->exact .3) 1/10) ===> 1/3 ; exact2461 (rationalize .3 1/10) ===> #i1/3 ; inexact24622463<procedure>(square z)</procedure>24642465Returns the square of z. This is equivalent to {{(* z z)}}-24662467 (square 42) ==> 17642468 (square 2.0) ==> 4.024692470<procedure>(exact-integer-sqrt k)</procedure>24712472Returns two non-negative exact integers s and r where k = s^2 + r and k < (s + 1)^2.24732474 (exact-integer-sqrt 4) ==> 2 02475 (exact-integer-sqrt 5) ==> 2 124762477<procedure>(expt z[1] z[2])</procedure><br>24782479Returns z[1] raised to the power z[2]. For z[1] != 024802481 z[1]^z[2] = e^z[2] log z[1]248224830^z is 1 if z = 0 and 0 otherwise.24842485<procedure>(exact z)</procedure><br>2486<procedure>(inexact z)</procedure><br>24872488The procedure {{inexact}} returns an inexact representation of z. The value returned is the inexact number that is numerically closest to the2489argument. For inexact arguments, the result is the same as the argument. For2490exact complex numbers, the result is a complex number whose real and imaginary2491parts are the result of applying inexact to the real and imaginary parts of the2492argument, respectively. If an exact argument has no reasonably close inexact2493equivalent (in the sense of =), then a violation of an implementation2494restriction may be reported.24952496The procedure {{exact}} returns an exact representation of z. The value returned is the exact number that is numerically closest to the2497argument. For exact arguments, the result is the same as the argument. For2498inexact non-integral real arguments, the implementation may return a rational2499approximation, or may report an implementation violation. For inexact complex2500arguments, the result is a complex number whose real and imaginary parts are2501the result of applying exact to the real and imaginary parts of the argument,2502respectively. If an inexact argument has no reasonably close exact equivalent,2503(in the sense of =), then a violation of an implementation restriction may be2504reported.25052506==== Numerical input and output25072508<procedure>(number->string z [radix])</procedure>25092510Radix must be an exact integer. The R7RS standard only requires2511implementations to support 2, 8, 10, or 16, but CHICKEN allows any2512radix between 2 and 36, inclusive (note: due to a bug, flonums with2513fractional components always use radix 10, irrespective of the argument).2514If omitted, radix defaults to 10. The procedure number->string takes2515a number and a radix and returns as a string an external2516representation of the given number in the given radix such that25172518 (let ((number number)2519 (radix radix))2520 (eqv? number2521 (string->number (number->string number2522 radix)2523 radix)))25242525is true. It is an error if no possible result makes this expression2526true.25272528If z is inexact, the radix is 10, and the above expression can be2529satisfied by a result that contains a decimal point, then the result2530contains a decimal point and is expressed using the minimum number of2531digits (exclusive of exponent and trailing zeroes) needed to make the2532above expression true [3, 5]; otherwise the format of the result is2533unspecified.25342535The result returned by number->string never contains an explicit radix2536prefix.25372538Note: The error case can occur only when z is not a complex2539number or is a complex number with a non-rational real or imaginary2540part.25412542Rationale: If z is an inexact number represented using flonums,2543and the radix is 10, then the above expression is normally2544satisfied by a result containing a decimal point. The unspecified2545case allows for infinities, NaNs, and non-flonum representations.25462547As an extension to R7RS, CHICKEN supports reading and writing the2548special IEEE floating-point numbers ''+nan'', ''+inf'' and ''-inf'',2549as well as negative zero.25502551<procedure>(string->number string)</procedure><br>2552<procedure>(string->number string radix)</procedure><br>25532554Returns a number of the maximally precise representation expressed by2555the given string. Radix must be an exact integer. The R7RS standard2556only requires implementations to support 2, 8, 10, or 16, but CHICKEN2557allows any radix between 2 and 36, inclusive. If supplied, radix is a2558default radix that may be overridden by an explicit radix prefix in2559string (e.g. "#o177"). If radix is not supplied, then the default2560radix is 10. If string is not a syntactically valid notation for a2561number, then string->number returns #f.25622563If the radix is higher than 18, the parser treats ambiguous syntax2564that might be a complex number, like {{{"+i"}}} and {{{"-i"}}} (and2565any prefixes like {{{"+1234i"}}}), as an integer. If you want this to2566be parsed as a complex number, explicitly write down {{{"0+i"}}} to2567disambiguate. Note that {{{number->string}}} will always emit complex2568numbers using the full notation, so it can always be read back by2569{{{string->number}}}.25702571 (string->number "100") ===> 1002572 (string->number "100" 16) ===> 2562573 (string->number "1e2") ===> 100.02574 (string->number "15##") ===> 1500.025752576Note: The domain of string->number may be restricted by2577implementations in the following ways. String->number is permitted2578to return #f whenever string contains an explicit radix prefix. If2579all numbers supported by an implementation are real, then string->2580number is permitted to return #f whenever string uses the polar or2581rectangular notations for complex numbers. If all numbers are2582integers, then string->number may return #f whenever the fractional2583notation is used. If all numbers are exact, then string->number may2584return #f whenever an exponent marker or explicit exactness prefix2585is used, or if a # appears in place of a digit. If all inexact2586numbers are integers, then string->number may return #f whenever a2587decimal point is used.25882589=== Other data types25902591This section describes operations on some of Scheme's non-numeric data2592types: booleans, pairs, lists, symbols, characters, strings and2593vectors.25942595==== Booleans25962597The standard boolean objects for true and false are written as #t and #f.2598What really matters, though, are the objects that the Scheme2599conditional expressions (if, cond, and, or, do) treat as true or false.2600The phrase "a true value" (or sometimes just "true") means any2601object treated as true by the conditional expressions, and the phrase2602"a false value" (or "false") means any object treated as false by2603the conditional expressions.26042605Of all the standard Scheme values, only #f counts as false in2606conditional expressions. Except for #f, all standard Scheme values,2607including #t, pairs, the empty list, symbols, numbers, strings,2608vectors, and procedures, count as true.26092610Note: Programmers accustomed to other dialects of Lisp should be2611aware that Scheme distinguishes both #f and the empty list from the2612symbol nil.26132614Boolean constants evaluate to themselves, so they do not need to be2615quoted in programs.26162617 #t ===> #t2618 #f ===> #f2619 '#f ===> #f26202621<procedure>(not obj)</procedure><br>26222623Not returns #t if obj is false, and returns #f otherwise.26242625 (not #t) ===> #f2626 (not 3) ===> #f2627 (not (list 3)) ===> #f2628 (not #f) ===> #t2629 (not '()) ===> #f2630 (not (list)) ===> #f2631 (not 'nil) ===> #f26322633<procedure>(boolean? obj)</procedure><br>26342635Boolean? returns #t if obj is either #t or #f and returns #f otherwise.26362637 (boolean? #f) ===> #t2638 (boolean? 0) ===> #f2639 (boolean? '()) ===> #f26402641<procedure>(boolean=? boolean[1] boolean[2] boolean[3] ...)</procedure>26422643Returns #t if all the arguments are #t or all are #f.26442645==== Pairs and lists26462647A pair (sometimes called a dotted pair) is a record structure with two2648fields called the car and cdr fields (for historical reasons). Pairs2649are created by the procedure cons. The car and cdr fields are accessed2650by the procedures car and cdr. The car and cdr fields are assigned by2651the procedures set-car! and set-cdr!.26522653Pairs are used primarily to represent lists. A list can be defined2654recursively as either the empty list or a pair whose cdr is a list.2655More precisely, the set of lists is defined as the smallest set X such2656that26572658* The empty list is in X.2659* If list is in X, then any pair whose cdr field contains list is2660 also in X.26612662The objects in the car fields of successive pairs of a list are the2663elements of the list. For example, a two-element list is a pair whose2664car is the first element and whose cdr is a pair whose car is the2665second element and whose cdr is the empty list. The length of a list is2666the number of elements, which is the same as the number of pairs.26672668The empty list is a special object of its own type (it is not a pair);2669it has no elements and its length is zero.26702671Note: The above definitions imply that all lists have finite2672length and are terminated by the empty list.26732674The most general notation (external representation) for Scheme pairs is2675the "dotted" notation (c[1] . c[2]) where c[1] is the value of the2676car field and c[2] is the value of the cdr field. For example (4 . 5)2677is a pair whose car is 4 and whose cdr is 5. Note that (4 . 5) is the2678external representation of a pair, not an expression that evaluates to2679a pair.26802681A more streamlined notation can be used for lists: the elements of the2682list are simply enclosed in parentheses and separated by spaces. The2683empty list is written () . For example,26842685 (a b c d e)26862687and26882689 (a . (b . (c . (d . (e . ())))))26902691are equivalent notations for a list of symbols.26922693A chain of pairs not ending in the empty list is called an improper2694list. Note that an improper list is not a list. The list and dotted2695notations can be combined to represent improper lists:26962697 (a b c . d)26982699is equivalent to27002701 (a . (b . (c . d)))27022703Whether a given pair is a list depends upon what is stored in the cdr2704field. When the set-cdr! procedure is used, an object can be a list one2705moment and not the next:27062707 (define x (list 'a 'b 'c))2708 (define y x)2709 y ===> (a b c)2710 (list? y) ===> #t2711 (set-cdr! x 4) ===> unspecified2712 x ===> (a . 4)2713 (eqv? x y) ===> #t2714 y ===> (a . 4)2715 (list? y) ===> #f2716 (set-cdr! x x) ===> unspecified2717 (list? x) ===> #f27182719Within literal expressions and representations of objects read by the2720read procedure, the forms '<datum>, `<datum>, ,<datum>, and ,@<datum>2721denote two-element lists whose first elements are the symbols quote,2722quasiquote, unquote, and unquote-splicing, respectively. The second2723element in each case is <datum>. This convention is supported so that2724arbitrary Scheme programs may be represented as lists. That is,2725according to Scheme's grammar, every <expression> is also a <datum>.2726Among other things, this permits the use of the read procedure to2727parse Scheme programs.27282729<procedure>(pair? obj)</procedure><br>27302731Pair? returns #t if obj is a pair, and otherwise returns #f.27322733 (pair? '(a . b)) ===> #t2734 (pair? '(a b c)) ===> #t2735 (pair? '()) ===> #f2736 (pair? '#(a b)) ===> #f27372738<procedure>(cons obj[1] obj[2])</procedure><br>27392740Returns a newly allocated pair whose car is obj[1] and whose cdr is2741obj[2]. The pair is guaranteed to be different (in the sense of eqv?)2742from every existing object.27432744 (cons 'a '()) ===> (a)2745 (cons '(a) '(b c d)) ===> ((a) b c d)2746 (cons "a" '(b c)) ===> ("a" b c)2747 (cons 'a 3) ===> (a . 3)2748 (cons '(a b) 'c) ===> ((a b) . c)27492750<procedure>(car pair)</procedure><br>27512752Returns the contents of the car field of pair. Note that it is an error2753to take the car of the empty list.27542755 (car '(a b c)) ===> a2756 (car '((a) b c d)) ===> (a)2757 (car '(1 . 2)) ===> 12758 (car '()) ===> error27592760<procedure>(cdr pair)</procedure><br>27612762Returns the contents of the cdr field of pair. Note that it is an error2763to take the cdr of the empty list.27642765 (cdr '((a) b c d)) ===> (b c d)2766 (cdr '(1 . 2)) ===> 22767 (cdr '()) ===> error27682769<procedure>(set-car! pair obj)</procedure><br>27702771Stores obj in the car field of pair. The value returned by set-car! is2772unspecified.27732774 (define (f) (list 'not-a-constant-list))2775 (define (g) '(constant-list))2776 (set-car! (f) 3) ===> unspecified2777 (set-car! (g) 3) ===> error27782779<procedure>(set-cdr! pair obj)</procedure><br>27802781Stores obj in the cdr field of pair. The value returned by set-cdr! is2782unspecified.27832784<procedure>(null? obj)</procedure><br>27852786Returns #t if obj is the empty list, otherwise returns #f.27872788<procedure>(list? obj)</procedure><br>27892790Returns #t if obj is a list, otherwise returns #f. By definition, all2791lists have finite length and are terminated by the empty list.27922793 (list? '(a b c)) ===> #t2794 (list? '()) ===> #t2795 (list? '(a . b)) ===> #f2796 (let ((x (list 'a)))2797 (set-cdr! x x)2798 (list? x)) ===> #f27992800<procedure>(make-list k [fill])</procedure>28012802Returns a newly allocated list of k elements. If a second argument is given, then each element is initialized to {{fill}}. Otherwise the initial contents of each element is unspecified.28032804 (make-list 2 3) ==> (3 3)28052806<procedure>(list obj ...)</procedure><br>28072808Returns a newly allocated list of its arguments.28092810 (list 'a (+ 3 4) 'c) ===> (a 7 c)2811 (list) ===> ()28122813<procedure>(length list)</procedure><br>28142815Returns the length of list.28162817 (length '(a b c)) ===> 32818 (length '(a (b) (c d e))) ===> 32819 (length '()) ===> 028202821<procedure>(append list ...)</procedure><br>28222823Returns a list consisting of the elements of the first list followed by2824the elements of the other lists.28252826 (append '(x) '(y)) ===> (x y)2827 (append '(a) '(b c d)) ===> (a b c d)2828 (append '(a (b)) '((c))) ===> (a (b) (c))28292830The resulting list is always newly allocated, except that it shares2831structure with the last list argument. The last argument may actually2832be any object; an improper list results if the last argument is not a2833proper list.28342835 (append '(a b) '(c . d)) ===> (a b c . d)2836 (append '() 'a) ===> a28372838<procedure>(reverse list)</procedure><br>28392840Returns a newly allocated list consisting of the elements of list in2841reverse order.28422843 (reverse '(a b c)) ===> (c b a)2844 (reverse '(a (b c) d (e (f))))2845 ===> ((e (f)) d (b c) a)28462847<procedure>(list-tail list k)</procedure><br>28482849Returns the sublist of list obtained by omitting the first k elements.2850It is an error if list has fewer than k elements. List-tail could be2851defined by28522853 (define list-tail2854 (lambda (x k)2855 (if (zero? k)2856 x2857 (list-tail (cdr x) (- k 1)))))28582859<procedure>(list-ref list k)</procedure><br>28602861Returns the kth element of list. (This is the same as the car of2862(list-tail list k).) It is an error if list has fewer than k elements.28632864 (list-ref '(a b c d) 2) ===> c2865 (list-ref '(a b c d)2866 (inexact->exact (round 1.8)))2867 ===> c28682869<procedure>(list-set! list k obj)</procedure>28702871It is an error if k is not a valid index of list.28722873The {{list-set!}} procedure stores obj in element k of list.28742875 (let ((ls (list 'one 'two 'five!)))2876 (list-set! ls 2 'three)2877 ls)2878 ==> (one two three)28792880 (list-set! '(0 1 2) 1 "oops")2881 ==> error ; constant list28822883<procedure>(memq obj list)</procedure><br>2884<procedure>(memv obj list)</procedure><br>2885<procedure>(member obj list [compare])</procedure><br>28862887These procedures return the first sublist of list whose car is obj,2888where the sublists of list are the non-empty lists returned by2889{{(list-tail list k)}} for k less than the length of list. If obj does not2890occur in list, then #f (not the empty list) is returned. {{memq}} uses {{eq?}}2891to compare obj with the elements of list, while {{memv}} uses {{eqv?}} and2892member {{compare}} if given, and {{equal?}} otherwise.28932894 (memq 'a '(a b c)) ===> (a b c)2895 (memq 'b '(a b c)) ===> (b c)2896 (memq 'a '(b c d)) ===> #f2897 (memq (list 'a) '(b (a) c)) ===> #f2898 (member (list 'a)2899 '(b (a) c)) ===> ((a) c)2900 (memq 101 '(100 101 102)) ===> unspecified2901 (memv 101 '(100 101 102)) ===> (101 102)29022903<procedure>(assq obj alist)</procedure><br>2904<procedure>(assv obj alist)</procedure><br>2905<procedure>(assoc obj alist [compare])</procedure><br>29062907Alist (for "association list") must be a list of pairs. These2908procedures find the first pair in alist whose car field is obj, and2909returns that pair. If no pair in alist has obj as its car, then #f (not2910the empty list) is returned. {{assq}} uses {{eq?}} to compare obj with the car2911fields of the pairs in alist, while {{assv}} uses {{eqv?}} and {{assoc}} uses2912{{compare}}, if given, otherwise {{equal?}}.29132914 (define e '((a 1) (b 2) (c 3)))2915 (assq 'a e) ===> (a 1)2916 (assq 'b e) ===> (b 2)2917 (assq 'd e) ===> #f2918 (assq (list 'a) '(((a)) ((b)) ((c))))2919 ===> #f2920 (assoc (list 'a) '(((a)) ((b)) ((c))))2921 ===> ((a))2922 (assq 5 '((2 3) (5 7) (11 13)))2923 ===> unspecified2924 (assv 5 '((2 3) (5 7) (11 13)))2925 ===> (5 7)29262927Rationale: Although they are ordinarily used as predicates, memq,2928memv, member, assq, assv, and assoc do not have question marks in2929their names because they return useful values rather than just #t2930or #f.29312932<procedure>(list-copy obj)</procedure>29332934Returns a newly allocated copy of the given obj if it is a list. Only the pairs themselves are copied; the cars of the result are the same (in the sense of {{eqv?}}) as the cars of list. If obj is an improper list, so is the result, and the final cdrs are the same in2935the sense of {{eqv?}}. An obj which is not a list is returned unchanged. It is an error if2936obj is a circular list.29372938 (define a '(1 8 2 8)) ; a may be immutable2939 (define b (list-copy a))2940 (set-car! b 3) ; b is mutable2941 b ==> (3 8 2 8)2942 a ==> (1 8 2 8)29432944==== Symbols29452946Symbols are objects whose usefulness rests on the fact that two symbols2947are identical (in the sense of eqv?) if and only if their names are2948spelled the same way. This is exactly the property needed to represent2949identifiers in programs, and so most implementations of Scheme use them2950internally for that purpose. Symbols are useful for many other2951applications; for instance, they may be used the way enumerated values2952are used in Pascal.29532954The rules for writing a symbol are exactly the same as the rules for2955writing an identifier.29562957It is guaranteed that any symbol that has been returned as part of a2958literal expression, or read using the read procedure, and subsequently2959written out using the write procedure, will read back in as the2960identical symbol (in the sense of eqv?). The string->symbol procedure,2961however, can create symbols for which this write/read invariance may2962not hold because their names contain special characters or letters in2963the non-standard case.29642965Note: Some implementations of Scheme have a feature known as2966"slashification" in order to guarantee write/read invariance for2967all symbols, but historically the most important use of this2968feature has been to compensate for the lack of a string data type.29692970Some implementations also have "uninterned symbols", which defeat2971write/read invariance even in implementations with slashification,2972and also generate exceptions to the rule that two symbols are the2973same if and only if their names are spelled the same.29742975<procedure>(symbol? obj)</procedure><br>29762977Returns #t if obj is a symbol, otherwise returns #f.29782979 (symbol? 'foo) ===> #t2980 (symbol? (car '(a b))) ===> #t2981 (symbol? "bar") ===> #f2982 (symbol? 'nil) ===> #t2983 (symbol? '()) ===> #f2984 (symbol? #f) ===> #f29852986<procedure>(symbol=? symbol[1] symbol[2] symbol[3] ...)</procedure>29872988Returns #t if all the arguments all have the same names in the sense of {{string=?}}.29892990Note: The definition above assumes that none of the arguments are uninterned symbols.29912992<procedure>(symbol->string symbol)</procedure><br>29932994Returns the name of symbol as a string. If the symbol was part of an2995object returned as the value of a literal expression (see2996"[[#literal-expressions|literal expressions]]") or by a call to the2997read procedure, and its name contains alphabetic characters, then the2998string returned will contain characters in the implementation's2999preferred standard case -- some implementations will prefer upper3000case, others lower case. If the symbol was returned by string->symbol,3001the case of characters in the string returned will be the same as the3002case in the string that was passed to string->symbol. It is an error3003to apply mutation procedures like string-set! to strings returned by3004this procedure.30053006The following examples assume that the implementation's standard case3007is lower case:30083009 (symbol->string 'flying-fish)3010 ===> "flying-fish"3011 (symbol->string 'Martin) ===> "martin"3012 (symbol->string3013 (string->symbol "Malvina"))3014 ===> "Malvina"30153016<procedure>(string->symbol string)</procedure><br>30173018Returns the symbol whose name is string. This procedure can create3019symbols with names containing special characters or letters in the3020non-standard case, but it is usually a bad idea to create such symbols3021because in some implementations of Scheme they cannot be read as3022themselves. See symbol->string.30233024The following examples assume that the implementation's standard case3025is lower case:30263027 (eq? 'mISSISSIppi 'mississippi)3028 ===> #t3029 (string->symbol "mISSISSIppi")3030 ===> the symbol with name "mISSISSIppi"3031 (eq? 'bitBlt (string->symbol "bitBlt"))3032 ===> #f3033 (eq? 'JollyWog3034 (string->symbol3035 (symbol->string 'JollyWog)))3036 ===> #t3037 (string=? "K. Harper, M.D."3038 (symbol->string3039 (string->symbol "K. Harper, M.D.")))3040 ===> #t30413042==== Characters30433044Characters are objects that represent printed characters such as3045letters and digits. Characters are written using the notation #\3046<character> or #\<character name>. For example:30473048Characters are written using the notation {{#\<character>}} or {{#\<character name>}}3049or {{#\x<hex scalar value>}}.30503051The following character names must be supported by all implementations with the3052given values. Implementations may add other names provided they cannot be3053interpreted as hex scalar values preceded by x.30543055 #\alarm ; U+00073056 #\backspace ; U+00083057 #\delete ; U+007F3058 #\escape ; U+001B3059 #\newline ; the linefeed character, U+000A3060 #\null ; the null character, U+00003061 #\return ; the return character, U+000D3062 #\space ; the preferred way to write a space3063 #\tab ; the tab character, U+000930643065Here are some additional examples:30663067 #\a ; lower case letter3068 #\A ; upper case letter3069 #\( ; left parenthesis3070 #\ ; the space character3071 #\space ; the preferred way to write a space3072 #\newline ; the newline character30733074Case is significant in #\<character>, but not in #\<character name>. If3075<character> in #\<character> is alphabetic, then the character3076following <character> must be a delimiter character such as a space or3077parenthesis. This rule resolves the ambiguous case where, for example,3078the sequence of characters "#\space" could be taken to be either a3079representation of the space character or a representation of the3080character "#\s" followed by a representation of the symbol "pace."30813082Characters written in the #\ notation are self-evaluating. That is,3083they do not have to be quoted in programs. Some of the procedures that3084operate on characters ignore the difference between upper case and3085lower case. The procedures that ignore case have "-ci" (for "case3086insensitive") embedded in their names.30873088<procedure>(char? obj)</procedure><br>30893090Returns #t if obj is a character, otherwise returns #f.30913092<procedure>(char=? char[1] char[2] char[3] ...)</procedure><br>3093<procedure>(char<? char[1] char[2] char[3] ...)</procedure><br>3094<procedure>(char>? char[1] char[2] char[3] ...)</procedure><br>3095<procedure>(char<=? char[1] char[2] char[3] ...)</procedure><br>3096<procedure>(char>=? char[1] char[2] char[3] ...)</procedure><br>30973098These procedures impose a total ordering on the set of characters. It3099is guaranteed that under this ordering:31003101* The upper case characters are in order. For example, (char<? #\A #\3102 B) returns #t.3103* The lower case characters are in order. For example, (char<? #\a #\3104 b) returns #t.3105* The digits are in order. For example, (char<? #\0 #\9) returns #t.3106* Either all the digits precede all the upper case letters, or vice3107 versa.3108* Either all the digits precede all the lower case letters, or vice3109 versa.31103111Some implementations may generalize these procedures to take more than3112two arguments, as with the corresponding numerical predicates.31133114<procedure>(char-ci=? char[1] char[2] char[3] ...)</procedure><br>3115<procedure>(char-ci<? char[1] char[2] char[3] ...)</procedure><br>3116<procedure>(char-ci>? char[1] char[2] char[3] ...)</procedure><br>3117<procedure>(char-ci<=? char[1] char[2] char[3] ...)</procedure><br>3118<procedure>(char-ci>=? char[1] char[2] char[3] ...)</procedure><br>31193120These procedures are similar to char=? et cetera, but they treat upper3121case and lower case letters as the same. For example, (char-ci=? #\A #\3122a) returns #t. Some implementations may generalize these procedures to3123take more than two arguments, as with the corresponding numerical3124predicates.31253126<procedure>(char-alphabetic? char)</procedure><br>3127<procedure>(char-numeric? char)</procedure><br>3128<procedure>(char-whitespace? char)</procedure><br>3129<procedure>(char-upper-case? letter)</procedure><br>3130<procedure>(char-lower-case? letter)</procedure><br>31313132These procedures return #t if their arguments are alphabetic, numeric,3133whitespace, upper case, or lower case characters, respectively,3134otherwise they return #f. The following remarks, which are specific to3135the ASCII character set, are intended only as a guide: The alphabetic3136characters are the 52 upper and lower case letters. The numeric3137characters are the ten decimal digits. The whitespace characters are3138space, tab, line feed, form feed, and carriage return.31393140<procedure>(char->integer char)</procedure><br>3141<procedure>(integer->char n)</procedure><br>31423143Given a character, char->integer returns an exact integer3144representation of the character. Given an exact integer that is the3145image of a character under char->integer, integer->char returns that3146character. These procedures implement order-preserving isomorphisms3147between the set of characters under the char<=? ordering and some3148subset of the integers under the <= ordering. That is, if31493150 (char<=? a b) ===> #t and (<= x y) ===> #t31513152and x and y are in the domain of integer->char, then31533154 (<= (char->integer a)3155 (char->integer b)) ===> #t31563157 (char<=? (integer->char x)3158 (integer->char y)) ===> #t31593160Note that {{integer->char}} does currently not detect3161a negative argument and will quietly convert {{-1}} to3162{{#x1ffff}} in CHICKEN.31633164==== Strings31653166Strings are sequences of characters. Strings are written as sequences of3167characters enclosed within quotation marks ("). Within a string literal,3168various escape sequences represent characters other than themselves. Escape3169sequences always start with a backslash (\):31703171* \a : alarm, U+000731723173* \b : backspace, U+000831743175* \t : character tabulation, U+000931763177* \n : linefeed, U+000A31783179* \r : return, U+000D31803181* \" : double quote, U+002231823183* \\ : backslash, U+005C31843185* \| : vertical line, U+007C31863187* \<intraline whitespace>*<line ending> <intraline whitespace>* : nothing31883189* \x<hex scalar value>; : specified character (note the terminating3190 semi-colon).31913192The result is unspecified if any other character in a string occurs after a3193backslash.31943195Except for a line ending, any character outside of an escape sequence stands3196for itself in the string literal. A line ending which is preceded by \3197<intraline whitespace> expands to nothing (along with any trailing intraline3198whitespace), and can be used to indent strings for improved legibility. Any3199other line ending has the same effect as inserting a \n character into the3200string.32013202Examples:32033204 "The word \"recursion\" has many meanings."3205 "Another example:\ntwo lines of text"3206 "Here's text \3207 containing just one line"3208 "\x03B1; is named GREEK SMALL LETTER ALPHA."32093210The length of a string is the3211number of characters that it contains. This number is an exact, non-negative3212integer that is fixed when the string is created. The valid indexes of a string3213are the exact non-negative integers less than the length of the string. The3214first character of a string has index 0, the second has index 1, and so on.32153216<procedure>(string? obj)</procedure><br>32173218Returns #t if obj is a string, otherwise returns #f.32193220<procedure>(make-string k)</procedure><br>3221<procedure>(make-string k char)</procedure><br>32223223Make-string returns a newly allocated string of length k. If char is3224given, then all elements of the string are initialized to char,3225otherwise the contents of the string are unspecified.32263227<procedure>(string char ...)</procedure><br>32283229Returns a newly allocated string composed of the arguments.32303231<procedure>(string-length string)</procedure><br>32323233Returns the number of characters in the given string.32343235<procedure>(string-ref string k)</procedure><br>32363237k must be a valid index of string. String-ref returns character k of3238string using zero-origin indexing.32393240<procedure>(string-set! string k char)</procedure><br>32413242k must be a valid index of string. String-set! stores char in element k3243of string and returns an unspecified value.32443245 (define (f) (make-string 3 #\*))3246 (define (g) "***")3247 (string-set! (f) 0 #\?) ===> unspecified3248 (string-set! (g) 0 #\?) ===> error3249 (string-set! (symbol->string 'immutable)3250 03251 #\?) ===> error32523253<procedure>(string=? string[1] string[2] string[3] ...)</procedure><br>32543255Returns #t if the two strings are the same length and contain the same3256characters in the same positions, otherwise returns #f.32573258<procedure>(string<? string[1] string[2] string[3] ...)</procedure><br>3259<procedure>(string>? string[1] string[2] string[3] ...)</procedure><br>3260<procedure>(string<=? string[1] string[2] string[3] ...)</procedure><br>3261<procedure>(string>=? string[1] string[2] string[3] ...)</procedure><br>32623263These procedures are the lexicographic extensions to strings of the3264corresponding orderings on characters. For example, string<? is the3265lexicographic ordering on strings induced by the ordering char<? on3266characters. If two strings differ in length but are the same up to the3267length of the shorter string, the shorter string is considered to be3268lexicographically less than the longer string.32693270<procedure>(substring string start [end])</procedure><br>32713272String must be a string, and start and end must be exact integers3273satisfying32743275 0 <= start <= end <= (string-length string)32763277Substring returns a newly allocated string formed from the characters3278of string beginning with index start (inclusive) and ending with index3279end (exclusive). The {{end}} argument is optional and defaults to the3280length of the string, this is a non-standard extension in CHICKEN.32813282<procedure>(string-append string ...)</procedure><br>32833284Returns a newly allocated string whose characters form the3285concatenation of the given strings.32863287<procedure>(string->list string [start [end]])</procedure><br>3288<procedure>(list->string list)</procedure><br>32893290String->list returns a newly allocated list of the characters that make3291up the given string between start and end. List->string returns a newly allocated string3292formed from the characters in the list list, which must be a list of3293characters. String->list and list->string are inverses so far as equal?3294is concerned.32953296<procedure>(string-copy string [start [end]])</procedure><br>32973298Returns a newly allocated copy of the given string.32993300<procedure>(string-copy! to at from [start [end]])</procedure>33013302It is an error if at is less than zero or greater than the length of to. It is also an error if {{(- (string-length to) at)}} is less than {{(- end start)}}.33033304Copies the characters of string from between start and end to string to, starting at3305at. The order in which characters are copied is unspecified, except that if the3306source and destination overlap, copying takes place as if the source is first3307copied into a temporary string and then into the destination. This can be3308achieved without allocating storage by making sure to copy in the correct3309direction in such circumstances.33103311 (define a "12345")3312 (define b (string-copy "abcde"))3313 (string-copy! b 1 a 0 2)3314 b ==> "a12de"33153316<procedure>(string-fill! string char +#!optional start end)</procedure><br>33173318Stores char in every element of the given string and returns an3319unspecified value. The optional start and end arguments specify3320the part of the string to be filled and default to the complete string.33213322==== Vectors33233324Vectors are heterogenous structures whose elements are indexed by3325integers. A vector typically occupies less space than a list of the3326same length, and the average time required to access a randomly chosen3327element is typically less for the vector than for the list.33283329The length of a vector is the number of elements that it contains. This3330number is a non-negative integer that is fixed when the vector is3331created. The valid indexes of a vector are the exact non-negative3332integers less than the length of the vector. The first element in a3333vector is indexed by zero, and the last element is indexed by one less3334than the length of the vector.33353336Vectors are written using the notation #(obj ...). For example, a3337vector of length 3 containing the number zero in element 0, the list (233382 2 2) in element 1, and the string "Anna" in element 2 can be written3339as following:33403341 #(0 (2 2 2 2) "Anna")33423343Vector constants are self-evaluating, so they do not need3344to be quoted in programs.33453346<procedure>(vector? obj)</procedure><br>33473348Returns #t if obj is a vector, otherwise returns #f.33493350<procedure>(make-vector k)</procedure><br>3351<procedure>(make-vector k fill)</procedure><br>33523353Returns a newly allocated vector of k elements. If a second argument is3354given, then each element is initialized to fill. Otherwise the initial3355contents of each element is unspecified.33563357<procedure>(vector obj ...)</procedure><br>33583359Returns a newly allocated vector whose elements contain the given3360arguments. Analogous to list.33613362 (vector 'a 'b 'c) ===> #(a b c)33633364<procedure>(vector-length vector)</procedure><br>33653366Returns the number of elements in vector as an exact integer.33673368<procedure>(vector-ref vector k)</procedure><br>33693370k must be a valid index of vector. Vector-ref returns the contents of3371element k of vector.33723373 (vector-ref '#(1 1 2 3 5 8 13 21)3374 5)3375 ===> 83376 (vector-ref '#(1 1 2 3 5 8 13 21)3377 (let ((i (round (* 2 (acos -1)))))3378 (if (inexact? i)3379 (inexact->exact i)3380 i)))3381 ===> 1333823383<procedure>(vector-set! vector k obj)</procedure><br>33843385k must be a valid index of vector. Vector-set! stores obj in element k3386of vector. The value returned by vector-set! is unspecified.33873388 (let ((vec (vector 0 '(2 2 2 2) "Anna")))3389 (vector-set! vec 1 '("Sue" "Sue"))3390 vec)3391 ===> #(0 ("Sue" "Sue") "Anna")33923393 (vector-set! '#(0 1 2) 1 "doe")3394 ===> error ; constant vector33953396<procedure>(vector->list vector [start [end]])</procedure><br>3397<procedure>(list->vector list)</procedure><br>33983399Vector->list returns a newly allocated list of the objects contained in3400the elements of vector. List->vector returns a newly created vector3401initialized to the elements of the list list.34023403 (vector->list '#(dah dah didah))3404 ===> (dah dah didah)3405 (list->vector '(dididit dah))3406 ===> #(dididit dah)34073408<procedure>(vector->string vector [start [end]])</procedure><br>3409<procedure>(string->vector string [start [end]])</procedure>34103411It is an error if any element of vector between start and end is not a character.34123413The vector->string procedure returns a newly allocated string of the objects3414contained in the elements of vector between start and end. The string->vector procedure returns a newly created vector initialized to3415the elements of the string string between start and end.34163417In both procedures, order is preserved.34183419 (string->vector "ABC") ==> #(#\A #\B #\C)3420 (vector->string #(#\1 #\2 #\3)) ==> "123"34213422<procedure>(vector-copy vector [start [end]])</procedure>34233424Returns a newly allocated copy of the elements of the given vector between3425start and end. The elements of the new vector are the same (in the sense of eqv?) as the3426elements of the old.34273428 (define a #(1 8 2 8)) ; a may be immutable3429 (define b (vector-copy a))3430 (vector-set! b 0 3) ; b is mutable3431 b ==> #(3 8 2 8)3432 (define c (vector-copy b 1 3))3433 c ==> #(8 2)34343435<procedure>(vector-copy! to at from [start [end]])</procedure>34363437It is an error if at is less than zero or greater than the length of to. It is also an error if {{(- (vector-length to) at)}} is less than {{(- end start)}}.34383439Copies the elements of vector from between start and end to vector to, starting at3440at. The order in which elements are copied is unspecified, except that if the3441source and destination overlap, copying takes place as if the source is first3442copied into a temporary vector and then into the destination. This can be3443achieved without allocating storage by making sure to copy in the correct3444direction in such circumstances.34453446 (define a (vector 1 2 3 4 5))3447 (define b (vector 10 20 30 40 50))3448 (vector-copy! b 1 a 0 2)3449 b ==> #(10 1 2 40 50)34503451<procedure>(vector-append vector ....)</procedure>34523453Returns a newly allocated vector whose elements are the concatenation of the3454elements of the given vectors.34553456 (vector-append #(a b c) #(d e f)) ==> #(a b c d e f)34573458<procedure>(vector-fill! vector fill [start [end]])</procedure>34593460The vector-fill! procedure stores fill in the elements of vector between start and3461end.34623463 (define a (vector 1 2 3 4 5))3464 (vector-fill! a 'smash 2 4)3465 a ==>#(1 2 smash smash 5)34663467==== Bytevectors34683469Bytevectors represent blocks of binary data. They are fixed-length sequences of3470bytes, where a byte is an exact integer in the range from 0 to 255 inclusive. A3471bytevector is typically more space-efficient than a vector containing the same3472values.34733474See [[Module (chicken bytevector)|The (chicken bytevector) module]] for more3475information. {{(scheme base)}} re-exports all R7RS-specific procedures from3476that module.34773478=== Control features34793480This chapter describes various primitive procedures which control the3481flow of program execution in special ways. The procedure? predicate is3482also described here.34833484<procedure>(procedure? obj)</procedure><br>34853486Returns #t if obj is a procedure, otherwise returns #f.34873488 (procedure? car) ===> #t3489 (procedure? 'car) ===> #f3490 (procedure? (lambda (x) (* x x)))3491 ===> #t3492 (procedure? '(lambda (x) (* x x)))3493 ===> #f3494 (call-with-current-continuation procedure?)3495 ===> #t34963497<procedure>(apply proc arg[1] ... args)</procedure><br>34983499Proc must be a procedure and args must be a list. Calls proc with the3500elements of the list (append (list arg[1] ...) args) as the actual3501arguments.35023503 (apply + (list 3 4)) ===> 735043505 (define compose3506 (lambda (f g)3507 (lambda args3508 (f (apply g args)))))35093510 ((compose sqrt *) 12 75) ===> 3035113512<procedure>(map proc list[1] list[2] ...)</procedure><br>35133514The lists must be lists, and proc must be a procedure taking as many3515arguments as there are lists and returning a single value. Map applies3516proc element-wise to the elements of the lists and returns a list of3517the results, in order. The dynamic order in which proc is applied to3518the elements of the lists is unspecified.35193520Like in SRFI-1, this procedure allows the arguments to be of unequal3521length; it terminates when the shortest list runs out. This is a3522CHICKEN extension to R7RS.35233524 (map cadr '((a b) (d e) (g h)))3525 ===> (b e h)35263527 (map (lambda (n) (expt n n))3528 '(1 2 3 4 5))3529 ===> (1 4 27 256 3125)35303531 (map + '(1 2 3) '(4 5 6)) ===> (5 7 9)35323533 (let ((count 0))3534 (map (lambda (ignored)3535 (set! count (+ count 1))3536 count)3537 '(a b))) ===> (1 2) or (2 1)35383539<procedure>(string-map proc string[1] string[2] ...)</procedure>35403541It is an error if proc does not accept as many arguments as there are strings and return a single character.35423543The string-map procedure applies proc element-wise to the elements of the3544strings and returns a string of the results, in order. If more than one3545string is given and not all strings have the same length, string-map terminates3546when the shortest string runs out. The dynamic order in which3547proc is applied to the elements of the3548strings is unspecified. If multiple returns occur from string-map, the values3549returned by earlier returns are not mutated.35503551 (string-map char-foldcase "AbdEgH") ==> "abdegh"35523553 (string-map3554 (lambda (c)3555 (integer->char (+ 1 (char->integer c))))3556 "HAL") ==> "IBM"35573558 (string-map3559 (lambda (c k)3560 ((if (eqv? k #\u) char-upcase char-downcase)3561 c))3562 "studlycaps xxx"3563 "ululululul") ==> "StUdLyCaPs"35643565<procedure>(vector-map proc vector[1] vector[2] ...)</procedure>35663567It is an error if proc does not accept as many arguments as there are vectors and return a single value.35683569The vector-map procedure applies proc element-wise to the elements of the3570vectors and returns a vector of the results, in order. If more than one3571vector is given and not all vectors have the same length, vector-map terminates3572when the shortest vector runs out. The dynamic order in which3573proc is applied to the elements of the3574vectors is unspecified. If multiple returns occur from vector-map, the values3575returned by earlier returns are not mutated.35763577 (vector-map cadr '#((a b) (d e) (g h)))3578 ==> #(b e h)35793580 (vector-map (lambda (n) (expt n n))3581 '#(1 2 3 4 5))3582 ==> #(1 4 27 256 3125)35833584 (vector-map + '#(1 2 3) '#(4 5 6 7))3585 ==> #(5 7 9)35863587 (let ((count 0))3588 (vector-map3589 (lambda (ignored)3590 (set! count (+ count 1))3591 count)3592 '#(a b))) ==> #(1 2) or #(2 1)35933594<procedure>(for-each proc list[1] list[2] ...)</procedure><br>35953596The arguments to for-each are like the arguments to map, but for-each3597calls proc for its side effects rather than for its values. Unlike map,3598for-each is guaranteed to call proc on the elements of the lists in3599order from the first element(s) to the last, and the value returned by3600for-each is unspecified.36013602 (let ((v (make-vector 5)))3603 (for-each (lambda (i)3604 (vector-set! v i (* i i)))3605 '(0 1 2 3 4))3606 v) ===> #(0 1 4 9 16)36073608Like in SRFI-1, this procedure allows the arguments to be of unequal3609length; it terminates when the shortest list runs out. This is a3610CHICKEN extension to R7RS.36113612<procedure>(string-for-each proc string[1] string[2] ...)</procedure>36133614It is an error if proc does not accept as many arguments as there are strings.3615The arguments to string-for-each are like the arguments to string-map, but3616string-for-each calls3617proc for its side effects rather than for its values. Unlike string-map,3618string-for-each is guaranteed to call3619proc on the elements of the3620strings in order from the first element(s) to the last, and the value returned3621by string-for-each is unspecified. If more than one3622string is given and not all strings have the same length, string-for-each3623terminates when the shortest string runs out. It is an error for3624proc to mutate any of the strings.36253626 (let ((v '()))3627 (string-for-each3628 (lambda (c) (set! v (cons (char->integer c) v)))3629 "abcde")3630 v) ==> (101 100 99 98 97)36313632<procedure>(vector-for-each proc vector[1] vector[2] ...)</procedure>36333634It is an error if proc does not accept as many arguments as there are vectors.3635The arguments to vector-for-each are like the arguments to vector-map, but3636vector-for-each calls3637proc for its side effects rather than for its values. Unlike vector-map,3638vector-for-each is guaranteed to call3639proc on the elements of the3640vectors in order from the first element(s) to the last, and the value returned3641by vector-for-each is unspecified. If more than one3642vector is given and not all vectors have the same length, vector-for-each3643terminates when the shortest vector runs out. It is an error for3644proc to mutate any of the vectors.36453646 (let ((v (make-list 5)))3647 (vector-for-each3648 (lambda (i) (list-set! v i (* i i)))3649 '#(0 1 2 3 4))3650 v) ==> (0 1 4 9 16)36513652<procedure>(call-with-current-continuation proc)</procedure><br>3653<procedure>(call/cc proc)</procedure><br>36543655Proc must be a procedure of one argument. The procedure3656call-with-current-continuation packages up the current continuation3657(see the rationale below) as an "escape procedure" and passes it as3658an argument to proc. The escape procedure is a Scheme procedure that,3659if it is later called, will abandon whatever continuation is in effect3660at that later time and will instead use the continuation that was in3661effect when the escape procedure was created. Calling the escape3662procedure may cause the invocation of before and after thunks installed3663using dynamic-wind.36643665The escape procedure accepts the same number of arguments as the3666continuation to the original call to call-with-current-continuation.3667Except for continuations created by the call-with-values procedure, all3668continuations take exactly one value. The effect of passing no value or3669more than one value to continuations that were not created by3670call-with-values is unspecified.36713672The escape procedure that is passed to proc has unlimited extent just3673like any other procedure in Scheme. It may be stored in variables or3674data structures and may be called as many times as desired.36753676The following examples show only the most common ways in which3677call-with-current-continuation is used. If all real uses were as simple3678as these examples, there would be no need for a procedure with the3679power of call-with-current-continuation.36803681 (call-with-current-continuation3682 (lambda (exit)3683 (for-each (lambda (x)3684 (if (negative? x)3685 (exit x)))3686 '(54 0 37 -3 245 19))3687 #t)) ===> -336883689 (define list-length3690 (lambda (obj)3691 (call-with-current-continuation3692 (lambda (return)3693 (letrec ((r3694 (lambda (obj)3695 (cond ((null? obj) 0)3696 ((pair? obj)3697 (+ (r (cdr obj)) 1))3698 (else (return #f))))))3699 (r obj))))))37003701 (list-length '(1 2 3 4)) ===> 437023703 (list-length '(a b . c)) ===> #f37043705Rationale:37063707A common use of call-with-current-continuation is for structured,3708non-local exits from loops or procedure bodies, but in fact3709call-with-current-continuation is extremely useful for implementing3710a wide variety of advanced control structures.37113712Whenever a Scheme expression is evaluated there is a continuation3713wanting the result of the expression. The continuation represents3714an entire (default) future for the computation. If the expression3715is evaluated at top level, for example, then the continuation might3716take the result, print it on the screen, prompt for the next input,3717evaluate it, and so on forever. Most of the time the continuation3718includes actions specified by user code, as in a continuation that3719will take the result, multiply it by the value stored in a local3720variable, add seven, and give the answer to the top level3721continuation to be printed. Normally these ubiquitous continuations3722are hidden behind the scenes and programmers do not think much3723about them. On rare occasions, however, a programmer may need to3724deal with continuations explicitly. Call-with-current-continuation3725allows Scheme programmers to do that by creating a procedure that3726acts just like the current continuation.37273728Most programming languages incorporate one or more special-purpose3729escape constructs with names like exit, return, or even goto. In37301965, however, Peter Landin [16] invented a general purpose escape3731operator called the J-operator. John Reynolds [24] described a3732simpler but equally powerful construct in 1972. The catch special3733form described by Sussman and Steele in the 1975 report on Scheme3734is exactly the same as Reynolds's construct, though its name came3735from a less general construct in MacLisp. Several Scheme3736implementors noticed that the full power of the catch construct3737could be provided by a procedure instead of by a special syntactic3738construct, and the name call-with-current-continuation was coined3739in 1982. This name is descriptive, but opinions differ on the3740merits of such a long name, and some people use the name call/cc3741instead.37423743<procedure>(values obj ...)</procedure><br>37443745Delivers all of its arguments to its continuation. Except for3746continuations created by the call-with-values procedure, all3747continuations take exactly one value. Values might be defined as3748follows:37493750 (define (values . things)3751 (call-with-current-continuation3752 (lambda (cont) (apply cont things))))37533754<procedure>(call-with-values producer consumer)</procedure><br>37553756Calls its producer argument with no values and a continuation that,3757when passed some values, calls the consumer procedure with those values3758as arguments. The continuation for the call to consumer is the3759continuation of the call to call-with-values.37603761 (call-with-values (lambda () (values 4 5))3762 (lambda (a b) b))3763 ===> 537643765 (call-with-values * -) ===> -137663767<procedure>(dynamic-wind before thunk after)</procedure><br>37683769Calls thunk without arguments, returning the result(s) of this call.3770Before and after are called, also without arguments, as required by the3771following rules (note that in the absence of calls to continuations3772captured using call-with-current-continuation the three arguments are3773called once each, in order). Before is called whenever execution enters3774the dynamic extent of the call to thunk and after is called whenever it3775exits that dynamic extent. The dynamic extent of a procedure call is3776the period between when the call is initiated and when it returns. In3777Scheme, because of call-with-current-continuation, the dynamic extent3778of a call may not be a single, connected time period. It is defined as3779follows:37803781* The dynamic extent is entered when execution of the body of the3782 called procedure begins.37833784* The dynamic extent is also entered when execution is not within the3785 dynamic extent and a continuation is invoked that was captured3786 (using call-with-current-continuation) during the dynamic extent.37873788* It is exited when the called procedure returns.37893790* It is also exited when execution is within the dynamic extent and a3791 continuation is invoked that was captured while not within the3792 dynamic extent.37933794If a second call to dynamic-wind occurs within the dynamic extent of3795the call to thunk and then a continuation is invoked in such a way that3796the afters from these two invocations of dynamic-wind are both to be3797called, then the after associated with the second (inner) call to3798dynamic-wind is called first.37993800If a second call to dynamic-wind occurs within the dynamic extent of3801the call to thunk and then a continuation is invoked in such a way that3802the befores from these two invocations of dynamic-wind are both to be3803called, then the before associated with the first (outer) call to3804dynamic-wind is called first.38053806If invoking a continuation requires calling the before from one call to3807dynamic-wind and the after from another, then the after is called3808first.38093810The effect of using a captured continuation to enter or exit the3811dynamic extent of a call to before or after is undefined. However,3812in CHICKEN it is safe to do this, and they will execute in the outer3813dynamic context of the {{dynamic-wind}} form.38143815 (let ((path '())3816 (c #f))3817 (let ((add (lambda (s)3818 (set! path (cons s path)))))3819 (dynamic-wind3820 (lambda () (add 'connect))3821 (lambda ()3822 (add (call-with-current-continuation3823 (lambda (c0)3824 (set! c c0)3825 'talk1))))3826 (lambda () (add 'disconnect)))3827 (if (< (length path) 4)3828 (c 'talk2)3829 (reverse path))))38303831 ===> (connect talk1 disconnect3832 connect talk2 disconnect)38333834=== Exceptions38353836This section describes Scheme's exception-handling and exception-raising3837procedures.38383839Exception handlers are one-argument procedures that determine the action the3840program takes when an exceptional situation is signaled. The system implicitly3841maintains a current exception handler in the dynamic environment.38423843The program raises an exception by invoking the current exception handler,3844passing it an object encapsulating information about the exception. Any3845procedure accepting one argument can serve as an exception handler and any3846object can be used to represent an exception.38473848<procedure>(with-exception-handler handler thunk)</procedure>38493850It is an error if handler does not accept one argument. It is also an error if3851thunk does not accept zero arguments.3852The with-exception-handler procedure returns the results of invoking3853thunk.3854Handler is installed as the current exception handler in the dynamic3855environment used for the invocation of3856thunk.38573858 (call-with-current-continuation3859 (lambda (k)3860 (with-exception-handler3861 (lambda (x)3862 (display "condition: ")3863 (write x)3864 (newline)3865 (k 'exception))3866 (lambda ()3867 (+ 1 (raise 'an-error))))))3868 ==> exception and prints "condition: an-error"38693870 (with-exception-handler3871 (lambda (x)3872 (display "something went wrong\n"))3873 (lambda ()3874 (+ 1 (raise 'an-error))))38753876prints "something went wrong"3877After printing, the second example then raises another exception.38783879<procedure>(raise obj)</procedure>38803881Raises an exception by invoking the current exception handler on3882obj. The handler is called with the same dynamic environment as that of the3883call to raise, except that the current exception handler is the one that was in3884place when the handler being called was installed. If the handler returns, a3885secondary exception is raised in the same dynamic environment as the handler.3886The relationship between3887obj and the object raised by the secondary exception is unspecified.38883889<procedure>(raise-continuable obj)</procedure>38903891Raises an exception by invoking the current exception handler on3892obj. The handler is called with the same dynamic environment as the call to3893raise-continuable, except that: (1) the current exception handler is the one3894that was in place when the handler being called was installed, and (2) if the3895handler being called returns, then it will again become the current exception3896handler. If the handler returns, the values it returns become the values3897returned by the call to raise-continuable.38983899 (with-exception-handler3900 (lambda (con)3901 (cond3902 ((string? con)3903 (display con))3904 (else3905 (display "a warning has been issued")))3906 42)3907 (lambda ()3908 (+ (raise-continuable "should be a number")3909 23)))3910 prints: "should be a number"3911 ==> 6539123913<procedure>(error [location] message obj ...)</procedure>39143915Message should be a string.3916Raises an exception as if by calling raise on a newly allocated3917implementation-defined object which encapsulates the information provided by3918message, as well as any3919objs, known as the irritants. The procedure error-object? must return #t on3920such objects.39213922 (define (null-list? l)3923 (cond ((pair? l) #f)3924 ((null? l) #t)3925 (else3926 (error3927 "null-list?: argument out of domain"3928 l))))39293930If location is given and a symbol, it indicates the name of the procedure where3931the error occurred.39323933<procedure>(error-object? obj)</procedure>39343935Returns #t if3936obj is an object created by error or one of an implementation-defined set of3937objects. Otherwise, it returns #f. The objects used to signal errors, including3938those which satisfy the predicates file-error? and read-error?, may or may not3939satisfy error-object?.39403941<procedure>(error-object-message error-object)</procedure>39423943Returns the message encapsulated by3944error-object.39453946<procedure>(error-object-irritants error-object)</procedure>39473948Returns a list of the irritants encapsulated by3949error-object.39503951<procedure>(read-error? obj)</procedure><br>3952<procedure>(file-error? obj)</procedure>39533954Error type predicates. Returns #t if3955obj is an object raised by the read procedure or by the inability to open an3956input or output port on a file, respectively. Otherwise, it returns #f.39573958=== Eval39593960<procedure>(eval expression [environment-specifier])</procedure><br>39613962Evaluates expression in the specified environment and returns its3963value. Expression must be a valid Scheme expression represented as3964data, and environment-specifier must be a value returned by one of the3965three procedures described below. Implementations may extend eval to3966allow non-expression programs (definitions) as the first argument and3967to allow other values as environments, with the restriction that eval3968is not allowed to create new bindings in the environments associated3969with null-environment or scheme-report-environment.39703971 (eval '(* 7 3) (scheme-report-environment 5))3972 ===> 2139733974 (let ((f (eval '(lambda (f x) (f x x))3975 (null-environment 5))))3976 (f + 10))3977 ===> 2039783979The {{environment-specifier}} is optional, and if not provided it3980defaults to the value of {{(interaction-environment)}}. This is a3981CHICKEN extension to R7RS, which, though strictly nonportable, is very3982common among Scheme implementations.39833984=== Input and output39853986==== Ports39873988Ports represent input and output devices. To Scheme, an input port is a Scheme3989object that can deliver data upon command, while an output port is a Scheme3990object that can accept data.39913992Different port types operate on different data. Scheme implementations are3993required to support textual ports and binary ports, but may also provide other3994port types.39953996A textual port supports reading or writing of individual characters from or to3997a backing store containing characters using read-char and write-char below, and3998it supports operations defined in terms of characters, such as read and write.39994000A binary port supports reading or writing of individual bytes from or to a4001backing store containing bytes using read-u8 and write-u8 below, as well as4002operations defined in terms of bytes. Whether the textual and binary port types4003are disjoint is implementation-dependent.40044005Ports can be used to access files, devices, and similar things on the host4006system on which the Scheme program is running.40074008<procedure>(call-with-port port proc)</procedure>40094010It is an error if4011proc does not accept one argument.4012The call-with-port procedure calls4013proc with4014port as an argument. If4015proc returns, then the port is closed automatically and the values yielded by4016the4017proc are returned. If40184019proc does not return, then the port must not be closed automatically unless it4020is possible to prove that the port will never again be used for a read or write4021operation.40224023 Rationale: Because Scheme's escape procedures have unlimited extent, it is4024 possible to escape from the current continuation but later to resume it. If4025 implementations were permitted to close the port on any escape from the4026 current continuation, then it would be impossible to write portable code4027 using both call-with-current-continuation and call-with-port.40284029Ports represent input and output devices. To Scheme, an input port is a4030Scheme object that can deliver characters upon command, while an output4031port is a Scheme object that can accept characters.40324033<procedure>(input-port? obj)</procedure><br>4034<procedure>(output-port? obj)</procedure><br>4035<procedure>(textual-port? obj)</procedure><br>4036<procedure>(binary-port? obj)</procedure><br>4037<procedure>(port? obj)</procedure>40384039These procedures return #t if4040obj is an input port, output port, textual port, binary port, or any kind of4041port, respectively. Otherwise they return #f.40424043<procedure>(input-port-open? port)</procedure><br>4044<procedure>(output-port-open? port)</procedure>40454046Returns #t if4047port is still open and capable of performing input or output, respectively, and4048#f otherwise.40494050<procedure>(current-input-port [port])</procedure><br>4051<procedure>(current-output-port [port])</procedure><br>4052<procedure>(current-error-port [port])</procedure><br>40534054Returns the current default input, output or error port.40554056If the optional {{port}} argument is passed, the current input or4057output port is changed to the provided port. It can also be used with4058{{parameterize}} to temporarily bind the port to another value. This4059is a CHICKEN extension to the R7RS standard.40604061Note that the default output port is not buffered. Use4062[[Module (chicken port)#set-buffering-mode!|{{set-buffering-mode!}}]]4063if you need a different behavior.40644065<procedure>(open-input-file filename [mode ...])</procedure><br>4066<procedure>(open-binary-input-file filename [mode ...])</procedure>40674068Takes a string naming an existing file and returns an input port4069capable of delivering textual or binary data from the file. If the file cannot be4070opened, an error is signalled.40714072Additional {{mode}} arguments can be passed in, which should be any of4073the keywords {{#:text}} or {{#:binary}}. These indicate the mode in4074which to open the file (this has an effect on non-UNIX platforms4075only). The extra {{mode}} arguments are CHICKEN extensions to the4076R7RS standard.40774078<procedure>(close-port port)</procedure><br>4079<procedure>(close-input-port port)</procedure><br>4080<procedure>(close-output-port port)</procedure><br>40814082Closes the resource associated with4083port, rendering the4084port incapable of delivering or accepting data. It is an error to apply the4085last two procedures to a port which is not an input or output port,4086respectively. Scheme implementations may provide ports which are simultaneously4087input and output ports, such as sockets; the close-input-port and4088close-output-port procedures can then be used to close the input and output4089sides of the port independently.40904091These routines have no effect if the port has already been closed.40924093<procedure>(open-input-string string)</procedure>40944095Takes a string and returns a textual input port that delivers characters from4096the string. If the string is modified, the effect is unspecified.40974098<procedure>(open-output-string)</procedure>40994100Returns a textual output port that will accumulate characters for retrieval by4101get-output-string.41024103<procedure>(get-output-string port)</procedure>41044105It is an error if4106port was not created with open-output-string.4107Returns a string consisting of the characters that have been output to the port4108so far in the order they were output. If the result string is modified, the4109effect is unspecified.41104111 (parameterize4112 ((current-output-port4113 (open-output-string)))4114 (display "piece")4115 (display " by piece ")4116 (display "by piece.")4117 (newline)4118 (get-output-string (current-output-port)))4119 ==> "piece by piece by piece.\n"41204121<procedure>(open-input-bytevector bytevector)</procedure>41224123Takes a bytevector and returns a binary input port that delivers bytes from the4124bytevector.41254126<procedure>(open-output-bytevector)</procedure>41274128Returns a binary output port that will accumulate bytes for retrieval by4129get-output-bytevector.41304131<procedure>(get-output-bytevector port)</procedure>41324133It is an error if4134port was not created with open-output-bytevector.4135Returns a bytevector consisting of the bytes that have been output to the port4136so far in the order they were output.41374138==== Input41394140If port is omitted from any input procedure, it defaults to the value returned by4141(current-input-port). It is an error to attempt an input operation on a closed4142port.41434144<procedure>(read-char [port])</procedure><br>41454146Returns the next character available from the input port, updating the4147port to point to the following character. If no more characters are4148available, an end of file object is returned. Port may be omitted, in4149which case it defaults to the value returned by current-input-port.41504151<procedure>(peek-char [port])</procedure><br>41524153Returns the next character available from the input port, without4154updating the port to point to the following character. If no more4155characters are available, an end of file object is returned. Port may4156be omitted, in which case it defaults to the value returned by4157current-input-port.41584159Note: The value returned by a call to peek-char is the same as4160the value that would have been returned by a call to read-char with4161the same port. The only difference is that the very next call to4162read-char or peek-char on that port will return the value returned4163by the preceding call to peek-char. In particular, a call to4164peek-char on an interactive port will hang waiting for input4165whenever a call to read-char would have hung.41664167<procedure>(read-line [port])</procedure>41684169Returns the next line of text available from the textual input4170port, updating the4171port to point to the following character. If an end of line is read, a string4172containing all of the text up to (but not including) the end of line is4173returned, and the port is updated to point just past the end of line. If an end4174of file is encountered before any end of line is read, but some characters have4175been read, a string containing those characters is returned. If an end of file4176is encountered before any characters are read, an end-of-file object is4177returned. For the purpose of this procedure, an end of line consists of either4178a linefeed character, a carriage return character, or a sequence of a carriage4179return character followed by a linefeed character. Implementations may also4180recognize other end of line characters or sequences.41814182<procedure>(eof-object? obj)</procedure><br>41834184Returns #t if obj is an end of file object, otherwise returns #f. The4185precise set of end of file objects will vary among implementations, but4186in any case no end of file object will ever be an object that can be4187read in using read.41884189<procedure>(eof-object)</procedure>41904191Returns an end-of-file object, not necessarily unique.41924193<procedure>(char-ready? [port])</procedure><br>41944195Returns #t if a character is ready on the input port and returns #f4196otherwise. If char-ready returns #t then the next read-char operation4197on the given port is guaranteed not to hang. If the port is at end of4198file then char-ready? returns #t. Port may be omitted, in which case it4199defaults to the value returned by current-input-port.42004201Rationale: Char-ready? exists to make it possible for a program4202to accept characters from interactive ports without getting stuck4203waiting for input. Any input editors associated with such ports4204must ensure that characters whose existence has been asserted by4205char-ready? cannot be rubbed out. If char-ready? were to return #f4206at end of file, a port at end of file would be indistinguishable4207from an interactive port that has no ready characters.42084209<procedure>(read-string k [port])</procedure>42104211See [[Module (chicken io)|(chicken io) module]] for more information.42124213<procedure>(read-u8 [port])</procedure>42144215Returns the next byte available from the binary input4216port, updating the4217port to point to the following byte. If no more bytes are available, an4218end-of-file object is returned.42194220<procedure>(peek-u8 [port])</procedure>42214222Returns the next byte available from the binary input4223port, but without updating the4224port to point to the following byte. If no more bytes are available, an4225end-of-file object is returned.42264227<procedure>(u8-ready? [port])</procedure>42284229Returns #t if a byte is ready on the binary input4230port and returns #f otherwise. If u8-ready? returns #t then the next read-u84231operation on the given4232port is guaranteed not to hang. If the4233port is at end of file then u8-ready? returns #t.42344235<procedure>(read-bytevector k [port])</procedure><br>4236<procedure>(read-bytevector! bytevector [port [start [end]]])</procedure>42374238See [[Module (chicken io)|(chicken io) module]] for more information.42394240==== Output42414242If port is omitted from any output procedure, it defaults to the value returned by4243(current-output-port). It is an error to attempt an output operation on a4244closed port.42454246<procedure>(newline)</procedure><br>4247<procedure>(newline port)</procedure><br>42484249Writes an end of line to port. Exactly how this is done differs from4250one operating system to another. Returns an unspecified value. The port4251argument may be omitted, in which case it defaults to the value4252returned by current-output-port.42534254<procedure>(write-char char)</procedure><br>4255<procedure>(write-char char port)</procedure><br>42564257Writes the character char (not an external representation of the4258character) to the given port and returns an unspecified value. The port4259argument may be omitted, in which case it defaults to the value4260returned by current-output-port.42614262<procedure>(write-string string [port [start [end]]])</procedurew>42634264Writes the characters of4265string from4266start to4267end in left-to-right order to the textual output4268port.42694270<procedure>(write-u8 byte [port])</procedure>42714272Writes the4273byte to the given binary output4274port and returns an unspecified value.42754276<procedure>(write-bytevector bytevector [port [start [end]]])</procedure>42774278See [[Module (chicken bytevector)|The (chicken bytevector) module]] for more4279information.42804281<procedure>(flush-output-port [port])</procedure>42824283Flushes any buffered output from the buffer of output-port to the underlying4284file or device and returns an unspecified value.42854286==== System interface42874288Questions of system interface generally fall outside of the domain of4289this report. However, the following operations are important enough to4290deserve description here.42914292<procedure>(features)</procedure>42934294Returns a list of the feature identifiers which cond-expand treats as true. It4295is an error to modify this list. Here is an example of what features might4296return:42974298 (features) ==>4299 (r7rs ratios exact-complex full-unicode4300 gnu-linux little-endian4301 fantastic-scheme4302 fantastic-scheme-1.04303 space-ship-control-system)43044305---4306Previous: [[Module scheme]]43074308Next: [[Module (scheme case-lambda)]]